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.
$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. });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With