[英]Wait for all $http requests to complete in Angular JS
我有一個頁面,可以根據變量的長度發出不同數量的$http
請求,然后我只想在所有請求完成后才將數據發送到作用域。 對於這個項目,我不想使用jQuery,所以請不要在你的答案中包含jQuery。 目前,當每個請求完成時,數據被發送到范圍,這不是我想要發生的。
這是我到目前為止的代碼的一部分。
for (var a = 0; a < subs.length; a++) {
$http.get(url).success(function (data) {
for (var i = 0; i < data.children.length; i++) {
rData[data.children.name] = data.children.age;
}
});
}
這是我對此持懷疑態度的部分,因為某些內容需要成為$q.all()
的參數,但在Angular的文檔中沒有提到它,我不確定它的含義是什么。
$q.all().then(function () {
$scope.rData = rData;
});
謝謝你的幫助。
$http
調用總是返回一個可以與$q.all
函數一起使用的$q.all
。
var one = $http.get(...);
var two = $http.get(...);
$q.all([one, two]).then(...);
您可以在文檔中找到有關此行為的更多詳細信息:
所有(許諾)
promises - 承諾的數組或散列。
在您的情況下,您需要創建一個數組並將所有調用推入循環中。 這樣,你可以在數組中使用$q.all(…)
,方法與上面的例子相同:
var arr = [];
for (var a = 0; a < subs.length; ++a) {
arr.push($http.get(url));
}
$q.all(arr).then(function (ret) {
// ret[0] contains the response of the first call
// ret[1] contains the second response
// etc.
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.