在Angular.js $ http请求之后,无论promise的成功与否,都调用complete函数

时间:2013-06-19 01:23:19

标签: ajax angularjs promise

如何使用Angular.js提供的promise API,无论$ http调用的结果如何,都能确保运行complete()函数?

$http({
    method: 'POST',
    url: submitUrl,
    data: $scope.data
})
.success(function(data) {
      // execute this code on success
})
.error(function(data) {
      // execute this code on error
})
.complete(function() {
  // execute this code regardless of outcome
});

一旦请求完成,可以使用它来隐藏AJAX微调器图标。无论请求结果如何,您都希望隐藏微调器。

3 个答案:

答案 0 :(得分:18)

我不是Angular.js中世界上最伟大的专家,但了解你可以做如下:

whatever.then(function() {
    // success code here
}, function() {
    // error code here
    return true; // return anything that's not undefined (and not a `throw()`) to force the chain down the success path at the following then().
}).then(function() {
    // "complete" code here
});

你基本上被迫从一个或多个.then()设计一些东西,这是$ q承诺的唯一方法。

答案 1 :(得分:12)

这取决于您想要做什么,但对于清理逻辑和类似情况,您也可以使用finally()来履行或拒绝您的承诺:

promise.finally(function () {
    // Do something regardless of outcome.
});

请注意,虽然finally()(以及其他一些图书馆)支持$q但不属于official draft

答案 2 :(得分:8)

如果您不关心请求是否成功,那么您可以将同一回调传递给successerror ...

   var cb = function(response){
      // do something
   };


   $http.post(submitUrl, $scope.data).success(cb).error(cb);

   // OR

   $http.post(submitUrl, $scope.data).then(cb, cb);

但请注意,successerror回调的签名与then回调的签名不同。

此外,模板引擎会以角度识别承诺,这意味着在模板中,您可以将附加到范围的承诺视为结果值。

这意味着你可以这样做:

控制器:

$scope.article = $http.get('/articles/' + articleId);

模板:

<article ng-cloak>
   <h3>{{article.title}}</h3>
   <div>{{article.content}}</div>
</article>

$http.get承诺得到解决时,视图会更新。

相关问题