Chaining Ajax calls in AngularJs

前端 未结 2 1515
我寻月下人不归
我寻月下人不归 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:28

    The accepted answer is good, but it doesn't explain the catch and finally methods which really put the icing on the cake. This great article on promises set me straight. Here's some sample code based on that article:

    $scope.spinner.start();
    
    $http.get('/whatever/123456')
      .then(function(response) {
         $scope.object1 = response.data;
         return $http.get('/something_else/?' + $scope.object1.property1);
      })
      .then(function(response) {
         $scope.object2 = response.data;
         if ($scope.object2.property88 == "a bad value")
            throw "Oh no! Something failed!";
         return $http.get('/a_third_thing/654321');
      })
      .then(function(response) {
         $scope.object3 = response.data;
      })
      .catch(function(error) {
         // this catches errors from the $http calls as well as from the explicit throw
         console.log("An error occured: " + error);
      })
      .finally(function() {
         $scope.spinner.stop();
      });
    

提交回复
热议问题