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

查看:34
本文介绍了等待所有 $http 请求在 Angular 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.

这是我目前的部分代码.

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() 的参数,但是在 Angular 的文档中没有提到它,我不确定是什么本来就是这样的.

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.all 函数一起使用的承诺.

$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(...);

您可以在文档中找到有关此行为的更多详细信息一个>:

You can find more details about this behaviour in the documentation:

所有(承诺)

promises - 承诺的数组或散列.

promises - An array or hash of promises.

在您的情况下,您需要创建一个数组并将所有调用推送到循环中.这样,您可以像上面的示例一样在数组上使用 $q.all(...) :

In your case you need to create an array and push all the calls into it in the loop. This way, you can use $q.all(…) on your array the same way as in the example above:

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 请求在 Angular JS 中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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