在AngularJs中链接Ajax调用

Ket*_*tan 35 angularjs

我想在链中进行多个Ajax调用.但我也希望在每次通话之后按下数据,然后再拨打下一个电话.最后,当所有调用成功时,我想运行一些其他代码.

我正在为我的Ajax调用使用Angular $ http服务,并希望坚持这一点.

可能吗?

pko*_*rce 53

是的,这是由AngularJS非常优雅地处理的,因为它的$http服务是围绕PromiseAPI构建的.基本上,对$http方法的调用会返回一个promise,您可以使用该then方法非常容易地链接promise .这是一个例子:

$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
   });
Run Code Online (Sandbox Code Playgroud)

您也可以将后处理和下一个$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
   });
Run Code Online (Sandbox Code Playgroud)

  • @Ketan`q.all`和这里描述的解决方案是两个不同的东西.`q.all`很棒,但仅适用于并行请求,也就是说,如果您不关心它们的顺序,并且一个请求不依赖于另一个请求的结果.根据您的问题,我了解到您在链接请求后,需要完成一个请求,您希望检查/处理结果,然后才发出另一个请求. (11认同)
  • 谢谢帕维尔,我会检查一下.现在,我使用`$ q.all`并且似乎正在做我想要的.但我也会尝试这个. (3认同)

Bre*_*ald 9

接受的答案是好的,但它没有解释捕获和最终真正把锦上添花的方法.这个诺言很大的文章让我直.以下是基于该文章的一些示例代码:

$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();
  });
Run Code Online (Sandbox Code Playgroud)