2017-05-08 69 views
0

在這段代碼中,我調用api。要求是從3 api獲取數據並聚合所有數據並顯示在表中。AngularJs同時調用API我不使用同一函數中的數據

var app = angular.module('myApp',[]);

app.controller('PersonController', function($scope,$http) { 
    $scope.arr1 =[]; 
     $scope.arr2 = []; 
     $scope.arr3 = []; 
     $scope.temp ; 


     function fetchAllBillable(){ 
      var me =$scope;   
      $http.get("http://echo.jsontest.com/insert-key-here/insert-value-here/key/value") 
       .then(function(response) { 
          $scope.temp = response.data; 

         console.log(me.temp); 

     }); 
     return $scope.temp; 

the value of scope.temp is undefined 
+0

您是否從您的服務獲得回覆? –

+0

是的,我在console.log(me.temp)中獲得響應,它寫在裏面,但沒有在http.get外部得到響應。 –

+0

確保你的return語句應該在函數內部(因爲我不能在你的函數中看到閉括號),並且它正在獲取初始臨時值。 –

回答

0

$http異步運行,所以外界then日誌語句也不會推出。

angular.module('plunker', []).controller('MainCtrl', function($http, $scope) { 
    $http.get('https://jsonplaceholder.typicode.com/posts/1') 
    .then(function(res) { 
     $scope.data = res.data; 
     console.log(res.data); // Object {...} 
    }); 
    console.log($scope.data); // undefined 
}); 

編輯:

您可以合併$ HTTP與承諾鏈接調用或$q.all

angular.module('plunker', []).controller('MainCtrl', function($http, $scope, $q) { 
    var users = 'https://jsonplaceholder.typicode.com/users/1'; 
    var comments = 'https://jsonplaceholder.typicode.com/comments/' 

    // Promise chaining 
    $http.get(users) 
    .then(function(res) { 
     $scope.user = res.data; 
     return $http.get(comments); 
    }) 
    .then(function(res) { 
     $scope.comments = res.data.slice(30) 
    }) 

    // $q.all 
    $q.all([ 
    $http.get(users), 
    $http.get(comments) 
    ]).then(function(resolves) { 
    // resolves[0] is users 
    // resolves[1] is comments 
    }) 
}); 
+0

在這種Summary.html我有寫控制器,其中數據從3 API來如下 可結算API 1. psbillableOffshore 2. offshoreManager1 緩衝API 1. psbufferOffshore 2. OffshoreManager 客戶端API 1.offshoreManager 2.clientBillingOffshore1 3.clientBillingOffshore2 在所有三個API管理器名稱是常見的。 我需要在表格中顯示。 1.offshoreManager 2.psbillableOffshore 3. psbufferOffshore 4.clientBillingOffshore1 5.clientBillingOffshore2 –

+0

在當我們顯示上的console.log(註釋)這個代碼的註釋;它顯示undefined.Can你查找問題 –

+0

我的錯誤,我有一段時間沒有使用'$ q.all'。回調中的參數是已解析數據的數組。 – Phix

0

我不知道,但在你的代碼所提供的結束標記是不正確的。此外,$http是異步調用(請參閱this堆棧溢出文章以獲取更多信息),因此代碼將在請求完成之前執行。

下面的代碼應該工作。

app.controller('PersonController', function($scope,$http) { 
    $scope.arr1 =[]; 
     $scope.arr2 = []; 
     $scope.arr3 = []; 
     $scope.temp ; 


     function fetchAllBillable(){ 
      var me =$scope;   
      $http.get("http://echo.jsontest.com/insert-key-here/insert-value-here/key/value") 
       .then(function(response) { 
          $scope.temp = response.data; 

         console.log(me.temp); 
         return $scope.temp; 

       }); 
     }; 
}; 
+0

它給我undefined.Is沒有辦法可以使用這個$ scope.temp並在此功能之後。 –

+0

不,沒有,我知道,這就是爲什麼有。然後。如果您嘗試返回** response.data **,會發生什麼情況? @sourabhlodha – Marc

+0

var abc = fetchAllBillable();警報(ABC');它打印未定義。我需要abc中的值才能進一步操作。 –

相關問題