Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

Thanks for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
111 views
Welcome To Ask or Share your Answers For Others

1 Answer

$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:

all(promises)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...