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

查看:1242
本文介绍了用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错误。现在,我使用angularjs与 $资源 $ HTTP 做我的(REST)请求到服务器。有什么办法来设置同样具有角一个全球性的错误处理程序?

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?

推荐答案

我还建设一个网站,角度和我遇到同样的阻碍全球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天全站免登陆