Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

Chaining Ajax calls in 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...