使用 AngularJS 的全局 Ajax 错误处理程序 [英] Global Ajax error handler with AngularJS

查看:32
本文介绍了使用 AngularJS 的全局 Ajax 错误处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的网站 100% 使用 jQuery 时,我曾经这样做过:

When my website was 100% jQuery, I used to do this:

$.ajaxSetup({
    global: true,
    error: function(xhr, status, err) {
        if (xhr.status == 401) {
           window.location = "./index.html";
        }
    }
});

为 401 错误设置全局处理程序.现在,我使用带有 $resource$http 的 angularjs 来向服务器发出(REST)请求.有没有办法类似地设置一个带有 angular 的全局错误处理程序?

to set a global handler for 401 errors. Now, I use angularjs with $resource and $http to do my (REST) requests to the server. Is there any way to similarly set a global error handler with angular?

推荐答案

我也在用 angular 构建一个网站,我在处理全局 401 时遇到了同样的障碍.当我看到这篇博文时,我最终使用了 http 拦截器.也许你会发现它和我一样有帮助.

I'm also building a website with angular and I came across this same obstacle for global 401 handling. I ended up using http interceptor when I came across this blog post. Maybe you'll find it as helpful as I did.

"基于 AngularJS(或类似)的应用程序中的身份验证.", espeo 软件

最终解决方案

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'], function ($routeProvider, $locationProvider, $httpProvider) {

    var interceptor = ['$rootScope', '$q', function (scope, $q) {

        function success(response) {
            return response;
        }

        function error(response) {
            var status = response.status;

            if (status == 401) {
                window.location = "./index.html";
                return;
            }
            // otherwise
            return $q.reject(response);

        }

        return function (promise) {
            return promise.then(success, error);
        }

    }];
    $httpProvider.responseInterceptors.push(interceptor);

这篇关于使用 AngularJS 的全局 Ajax 错误处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆