angular $http / jquery complete equivalent

旧城冷巷雨未停 提交于 2020-01-11 08:05:14

问题


Is there a way to emulate jquery 'complete' callback with angular $http module? I have some code I would like to execute no matter whether the request succeeded or failed and at the moment I find myself having to write this:

$http.get(someUrl).success(function(){
        successCode();
        completeCode();
    }).error(function(){
        errorCode();
        completeCode();
    })

but I would rather write something like:

$http.get(someUrl).success(function(){
        successCode();
    }).error(function(){
        errorCode();
    }).complete(function(){
        completeCode();
    })

I've tried also using the promise API but I end up having the same problem. Any suggestion?


回答1:


Update Aug 2014: .always has been renamed .finally in recent versions of Angular. Prefer .finally to .always.

Note that in order to support IE8 you have to call it with bracket notation as ["finally"].


You can use .always in AngularJS

This change is rather new (you could do that in jQuery for a while), you can see the commit here. This requires you to have AngularJS 1.1.5 or higher.

always(callback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.

Fiddle



来源:https://stackoverflow.com/questions/18144212/angular-http-jquery-complete-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!