一个请求中多个ajax,在另一个Ajax请求中处理多个Ajax请求

我使用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 –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值