简体   繁体   English

角度相当于jQuery deferred.always()回调

[英]Angular equivalent of jQuery deferred.always() callback

We can handle response with .always() callback function in jQuery whether response is success or not. 我们可以在jQuery中使用.always()回调函数处理响应,无论响应是否成功。

Is there an equivalent of this type of usage in AngularJS? 在AngularJS中是否存在这种类型的用法?

//jQuery
$.get( "test.php" ).always(function() {
  alert( "$.get completed with success or error callback arguments" );
});

//AngularJS
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    //success
  }, function errorCallback(response) {
    //error
  });

//how can i handle always?

您可以使用Angular promise的finally方法

The finally() method from $q service used for this: $ q服务的finally()方法用于此:

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    //success
}).catch(function errorCallback(response) {
    //error
}).finally(function() {
    //Callback method
    //Executed always, no matter of success or fail
});

An important notice when returning promises from finally() callback: finally()回调返回promise时的一个重要注意事项:

finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. finally返回一个承诺,它将以与承诺相同的履行价值或拒绝原因得到解决。 However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. 但是,如果callback返回一个promise,则返回的promise的解析将被延迟,直到从callback返回的promise完成为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM