2015-02-10 41 views
0

內呼籲環路我試圖創建一個離子應用,爲此我必須做出內部一些HTTP GET請求循環,但似乎角之前不會等待數據展示他們。API的角度

這是我正在使用的代碼。

$http.get(ApiUrl.get() + '/Threads' + '?access_token=' + $scope.userToken + filterString + "&filter[order]=created%20desc") 
.success(function(data, status, headers, config) { 

    var i=0; 

    for(thread in data) 
    { 
     $scope.threadObj = data[i]; 
     var threadId = $scope.threadObj.id; 
     $scope.threadPostNumber; 

     //On récupére chaque nombre de post 
     $http.get(ApiUrl.get() + '/Threads/' + threadId + '/posts/count' + '?access_token=' + $scope.userToken) 
      .success(function(data, status, headers, config) { 
       $scope.threadPostNumber = data.count; 
      }) 
      .error(function(data, status, headers, config) { 
       alert("Connection error, please try again."); 
       $location.path("/app/carte"); 
      }); 

     $scope.threadObj.count = $scope.threadPostNumber; 
     $scope.threads[i] = $scope.threadObj; 

     i++; 
    } 
}) 
.error(function(data, status, headers, config) { 
    alert("Connection error, please try again."); 
    $location.path("/app/carte"); 
}); 

第一HTTP GET完成並且數據可以在foreach內展示,但是當我嘗試其它附加數據添加到原有的以創建第二GET請求沒有或者有時候只有最後一個值顯示每一個。

+0

不幸的是,你不能像這樣使用$ http。 http://stackoverflow.com/a/17366158/3980115 – Vlad274 2015-02-10 22:12:14

+0

@ Vlad274,有沒有辦法做到這一點,沒有localstorage? – PeterFour 2015-02-10 22:15:16

回答

3

問題源於API調用是異步的,比for循環慢得多。

$http.get發佈請求,但直到for循環完成後纔得到響應。隨着承諾成功回調中的結果$scope.threadPostNumber將被設置在一個分配後:

$scope.threadObj.count = $scope.threadPostNumber 

所以有效這項任務是沒用的。

爲了修復,使用尾遞歸或Promise objects 爲了使呼叫連續。

你也可以適當範圍當前線程對象,以便當許成功,你會被修改正確的線程:

$http.get(ApiUrl.get() + '/Threads' + '?access_token=' + $scope.userToken + filterString + "&filter[order]=created%20desc") 
.success(function(data, status, headers, config) { 

    data.forEach(function(thread, i) { 

     $scope.threads[i] = thread; 

     var threadId = thread.id; 

     $http.get(ApiUrl.get() + '/Threads/' + threadId + '/posts/count?access_token=' + $scope.userToken) 
      .success(function(data, status, headers, config) { 

       $scope.threads[i].count = data.count; 
      }) 
      .error(function(data, status, headers, config) { 

       alert('Connetion error, please try again.'); 
       $location.path('/app/carte'); 
      }); 
    }); 
}) 
.error(function(data, status, headers, config) { 
    alert("Connection error, please try again."); 
    $location.path("/app/carte"); 
}); 

由於這種使用forEachsee the MDN page),threadi被限定在功能,因此對於該函數的生命週期以及它調用或創建的任何函數(如承諾成功回調),threadi將保留傳遞給該函數的值。這可以確保無論HTTP請求的返回順序如何,您都將在正確的線程上設置count