Angular 相当于 jQuery deferred.always() 回调
Angular equivalent of jQuery deferred.always() callback
无论响应是否成功,我们都可以在jQuery中用.always()回调函数处理响应。
在 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 promises 的 finally
method。
用于此的 finally() method from $q 服务:
$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
});
从 finally()
回调返回承诺时的重要通知:
finally
returns a promise, which will become resolved with the same
fulfillment value or rejection reason as promise. However, if callback
returns a promise, the resolution of the returned promise will be
delayed until the promise returned from callback is finished.
无论响应是否成功,我们都可以在jQuery中用.always()回调函数处理响应。
在 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 promises 的 finally
method。
用于此的 finally() method from $q 服务:
$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
});
从 finally()
回调返回承诺时的重要通知:
finally
returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, ifcallback
returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished.