本文介绍了angular $http/jquery 完全等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用 angular $http 模块模拟 jquery 'complete' 回调?无论请求是成功还是失败,我都想执行一些代码,目前我发现自己必须编写以下代码:

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();
    })

我也尝试过使用 promise API,但最终还是遇到了同样的问题.有什么建议吗?

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

推荐答案

2014 年 8 月更新: .always 已更名为 .finally最新版本的 Angular.更喜欢 .finally.always.

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

请注意,为了支持 IE8,您必须使用括号表示法将其称为 ["finally"].

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

你可以在 AngularJS 中使用 .always

You can use .always in AngularJS

这个变化相当新(你可以在 jQuery 中做一段时间),你可以看到提交 此处.这要求您拥有 AngularJS 1.1.5 或更高版本.

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) – 允许您观察承诺的履行或拒绝,但这样做而不修改最终值.这对于释放资源或做一些事情很有用无论承诺被拒绝还是解决,都需要进行清理.请参阅完整规范更多信息.

这篇关于angular $http/jquery 完全等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 03:33