等待所有$ http请求的角JS完成 [英] Wait for all $http requests to complete in Angular JS

查看:130
本文介绍了等待所有$ http请求的角JS完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页比可以根据一个变量的长度不同数量的 $ HTTP 的请求,然后我想将数据发送到范围仅当所有的请求都完成了。对于这个项目,我不想使用jQuery,所以请不要在你的答案包括jQuery的。此刻,数据被发送到的范围,因为每个请求的完成,这是不是我希望发生

I have a page than can make a different number of $http requests depending on the length of a variables, and then I want to send the data to the scope only when all the requests are finished. For this project I do not want to use jQuery, so please do not include jQuery in your answer. At the moment, the data is sent to the scope as each of the requests finish, which isn't what I want to happen.

下面是code我到目前为止的一部分。

Here is part of the code I have so far.

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一个参数(),但它未在文档的提及角,而且我不确定这是什么意思是。

Here is the part that I am sceptical about, because something needs to be an argument for $q.all(), but it is not mentioned on the docs for Angular and I am unsure what it is meant to be.

$q.all().then(function () {
  $scope.rData = rData;
});

感谢您的帮助。

推荐答案

$ HTTP 电话始终返回可与 $ Q使用的承诺。所有功能。

$http call always returns a promise which can be used with $q.all function.

var one = $http.get(...);
var two = $http.get(...);

$q.all([one, two]).then(...);

借助文档是pretty明确一下:

The documentation is pretty clear about it:

所有的(承诺)

承诺 - 承诺的数组或哈希

promises - An array or hash of promises.

在你的情况,你需要创建一个数组和所有的通话推入它的循环:

In your case you need to create an array and push all the calls into it in the loop:

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.
});

这篇关于等待所有$ http请求的角JS完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆