[英]chained angularjs $http requests within for each loop
我需要檢查所有$ http請求處理的“ for循環”功能何時完成,並且可以一勞永逸地刷新數據網格。 當前,刷新是針對每個$ http請求進行的,這是不希望的行為。
已經閱讀了有關angularjs $ q.all的一些知識,但不確定在以下情況下的實現。
任何幫助/建議,我們將不勝感激。 提前致謝。
這是代碼段-
function chainedAjax(param1, param2) {
var something = something;
$http({
// processing
}).then(function(responseData) {
// processing
return $http({
// processing
});
}, function(ex) {
// error
}).then(function(responseData) {
// processing
return $http({
// processing
});
}, function(ex) {
// error
}).then(function(responseData) {
// success - Done
finish();
}, function(ex) {
// error
});
}
function init(selectedDocs) {
var something = something;
angular.forEach(selectedDocs, function(item, arrayIndex) {
chainedAjax(item.param1, item.param2);
});
}
function finish() {
refreshDocsTable(); // refreshes the current grid
}
init(selectedItems); // call init function
假設您實際上對每個項目都需要多個請求,則需要類似以下的內容:
function chainedAjax(param1, param2) {
var something = something;
return $http({})
.then(function(responseData) {
// processing
return $http({});
})
.then(function(responseData) {
// processing
return $http({});
})
}
function dealWithError(error) {}
function init(selectedDocs) {
var something = something;
var requests = [];
angular.forEach(selectedDocs, function(item) {
requests.push(chainedAjax(item.param1, item.param2));
});
$q.all(requests)
.then(finish)
.catch(dealWithError);
}
代碼有點模糊,無法給出一個很好的答案,但是我假設您在chainedAjax函數中的外部$ http調用是您要檢測執行x次的代碼。 似乎也有一些內部的$ http調用,我假設這些是您想要擺脫的。 您可以執行以下操作:
function chainedAjax(param1, param2) {
var something = something;
return $http({
// processing
}).then(function(responseData) {
// processing
}, function(ex) {
// error
}).then(function(responseData) {
// processing
}, function(ex) {
// error
}).then(function(responseData) {
// success - Done
finish();
}, function(ex) {
// error
});
}
function init(selectedDocs) {
var something = something;
var count = 0, target = selectedDocs.length - 1;
angular.forEach(selectedDocs, function(item, arrayIndex) {
chainedAjax(item.param1, item.param2).then(function(){
count++;
if(count == target){
// All requests are done
// Now make one final call to update datatable
$http({
// parameters
}).then(function(response){
});
}
}).catch(function(err){
// A single http request failed, if you want to count that as well, uncomment the line below
// count++;
});
});
}
由於$ http已經返回了一個Promise,因此您不需要在請求完成時使用$ q發出信號。 讓我知道答案是否指向正確的方向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.