我使用angularjs的$ http方法获取多个“父”元素。在这个Ajax调用.success方法中,我必须迭代父元素,并对每个父元素使用另一个Ajax调用来获取其各自的子元素。我最终想要的是一个包含所有子元素对象的数组,因此我可以使用ng-repeat来显示它们。这就是为什么我要首先收集数组中的所有子元素,并将该数组写入到我用来显示的范围数组中,所以角度只会在收集所有子元素时更新。我并不擅长使用承诺,但我认为这应该可以通过使用它们。结构基本上是:在另一个Ajax请求中处理多个Ajax请求
.success(function(parentElements){
var tempChildElements = [];
$.each(parentElements, function(i, parentElement){
getChildElements(parentElement)
.success(function(childElements){
tempChildElements.concat(childElements);
})
})
});
$scope.childElements = tempChildElements;
});
基本上,我需要知道什么时候jQuery.each中的所有请求都完成了。
编辑:
于是,我改变了我的代码,以将您的答案,我想我接近,但它仍然没有工作。我得到的是:
$scope.loadChildren = function(){
var tempchildren = [];
var promises = [];
restApi.getOwnparents() //Returns $http.get promise
.then(function(parents){
parents.data.forEach(function(parent, i, parents){
promises.push(restApi.getOwnchildren(parent) //Returns $http.get promise
.then(function(children){
tempchildren = tempchildren.concat(children.data);
},function(msg){
console.log(msg);
}));
});
}, function(msg){
console.log(msg);
});
$q.all(promises).then(function(data){
//Never gets called
$scope.currentElements = tempchildren;
console.log(tempchildren);
});
};
编辑2: 我得到了它使用从你们的建议的工作,下面是我的代码。随意分享改进。
$scope.loadparents = function(){
var tempchildren = [];
var promises = [];
restApi.getOwnparents()
.then(function(parents){
parent.data.forEach(function(parent, i, parents){
promises.push(restApi.getOwnchildren(parent));
});
$q.all(promises).then(function(data){
console.log(data);
data.forEach(function(children){
tempchildren = tempchildren.concat(children.data);
});
$scope.currentElements = tempchildren;
});
});
};
2015-10-15
Cuddl3s
+0
首先摆脱'$,each'如果'parentelements'是一个数组,你可以使用本地'forEach',否则使用'angular.forEach'。看看'$ q.all'它会在所有解决方案调用它的'then'后运行一系列promise –