【问题标题】:Chaining Ajax calls in AngularJs在 AngularJs 中链接 Ajax 调用
【发布时间】:2016-05-12 09:30:54
【问题描述】:

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

我正在为我的 Ajax 调用使用 Angular $http 服务,并希望坚持下去。

有可能吗?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    是的,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
       });
    

    你也可以将后处理和下一个$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
       });
    

    【讨论】:

    • 谢谢帕维尔,我会去看看。现在,我使用了$q.all,似乎正在做我想做的事。但我也会试试这个。
    • @Ketan q.all 和这里描述的解决方案是两个不同的东西。 q.all 很棒,但仅适用于并行请求,也就是说,如果您不关心它们的顺序并且一个请求不依赖于另一个请求的结果。从您的问题中,我了解到您在链接请求之后,其中一个请求需要完成,您想要检查/处理结果,然后才发出另一个请求。
    • 在我的特殊问题中,并行运行它们是可以的,但我真正想要的是在所有代码都完成后运行一些代码。但是,您的回答仍然很有价值,因为我相信我迟早会遇到这个问题。我会接受你的回答。
    【解决方案2】:

    公认的答案很好,但它没有解释真正锦上添花的捕获和最终方法。这个great article on 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();
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 2017-04-07
      • 2013-07-26
      • 2017-08-26
      • 1970-01-01
      相关资源
      最近更新 更多