Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining Ajax calls in AngularJs

Tags:

angularjs

I would like to make multiple Ajax calls in a chain. But I also would like to massage the data after each call before making the next call. In the end, when All calls are successful, I would like to run some other code.

I am using Angular $http service for my Ajax calls and would like to stick to that.

Is it possible?

like image 685
Ketan Avatar asked Apr 29 '13 17:04

Ketan


1 Answers

Yes, this is handled very elegantly by AngularJS since its $http service is built around the PromiseAPI. Basically, calls to $http methods return a promise and you can chain promises very easily by using the then method. Here is an example:

$http.get('http://host.com/first')    .then(function(result){     //post-process results and return     return myPostProcess1(result.data);     })    .then(function(resultOfPostProcessing){     return $http.get('http://host.com/second');     })    .then(function(result){     //post-process results of the second call and return     return myPostProcess2(result.data);     })    .then(function(result){       //do something where the last call finished    }); 

You could also combine post-processing and next $http function as well, it all depends on who is interested in the results.

$http.get('http://host.com/first')    .then(function(result){     //post-process results and return promise from the next call     myPostProcess1(result.data);      return $http.get('http://host.com/second');     })    .then(function(secondCallResult){      //do something where the second (and the last) call finished    }); 
like image 74
pkozlowski.opensource Avatar answered Oct 21 '22 08:10

pkozlowski.opensource