Chaining Ajax calls in AngularJs

前端 未结 2 1507
我寻月下人不归
我寻月下人不归 2020-11-28 05:41

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

2条回答
  •  春和景丽
    2020-11-28 06:31

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

提交回复
热议问题