Подтвердить что ты не робот

Цепочка Ajax вызывает в AngularJs

Я хотел бы сделать несколько вызовов Ajax в цепочке. Но я также хотел бы массировать данные после каждого вызова, прежде чем делать следующий звонок. В конце концов, когда вызовы Все успешны, я хотел бы запустить другой код.

Я использую Angular $http service для своих вызовов Ajax и хотел бы придерживаться этого.

Возможно ли это?

4b9b3361

Ответ 1

Да, это очень элегантно обрабатывается AngularJS, поскольку его служба $http построена вокруг PromiseAPI. В принципе, призывы к методам $http возвращают обещание, и вы можете легко сцедить promises с помощью метода then. Вот пример:

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

Вы также можете комбинировать пост-обработку и следующую функцию $http, все зависит от того, кто заинтересован в результатах.

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

Ответ 2

Принятый ответ хорош, но он не объясняет улов и, наконец, методы, которые действительно ставят глазурь на торт. Эта отличная статья на promises установила меня прямо. Вот пример кода на основе этой статьи:

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