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

Jus*_*tin 12 ajax promise angularjs

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

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

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

Bee*_*oot 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
});
Run Code Online (Sandbox Code Playgroud)

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


ber*_*rdw 12

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

promise.finally(function () {
    // Do something regardless of outcome.
});
Run Code Online (Sandbox Code Playgroud)

请注意,虽然(和其他一些图书馆)finally()支持,但$q不是正式草案的一部分.


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

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

此外,模板中的模板引擎可以识别promises,这意味着在模板中,您可以将附加到范围的promise视为结果值.

这意味着你可以这样做:

控制器:

$scope.article = $http.get('/articles/' + articleId);
Run Code Online (Sandbox Code Playgroud)

模板:

<article ng-cloak>
   <h3>{{article.title}}</h3>
   <div>{{article.content}}</div>
</article>
Run Code Online (Sandbox Code Playgroud)

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