Kuan
Kuan

Reputation: 11389

How to detect all request finished in AngularJS

All:

I wonder how can I arrange $http request order and detect the finish point when all request finished, what I want to do is like:

Firstly init a request to get a json which include lots of images name and their url, then fetch them one by one( or together). When all image data ready, start to render the page to show all images.

Thanks

Upvotes: 0

Views: 1560

Answers (2)

Boris Charpentier
Boris Charpentier

Reputation: 3545

$http is a promise, and you can chain them. It could look like this :

$http.get('path').then(function (result){
    //do something with result
    return $http.get('path two');
}).then(function(result){
    //result is the resolve promise of $http.get('path two');
});

[EDIT]

I think I found something better in your case : $q.all

So you can iterate over an array of path, create promises, call the all and wait for them all to finish, I didn't try it but it should look like :

var list = ['path', 'path two'];
var promises = [];
for (var i = list.length - 1; i >= 0; i--) {
  promises.push($http.get(list[i]));
}; 

$q.all(promises).then(function(results){
  //results is an array, ordered like the promises array
});

Upvotes: 1

bamboo_inside
bamboo_inside

Reputation: 462

if you want to make sure that no requests are going through, you could use this (useful for multiple requests):

$rootScope.isLoading = function () {
    return $http.pendingRequests.length > 0;
};

Upvotes: 0

Related Questions