Global Ajax error handler with AngularJS
当我的网站是100%jQuery时,我曾经这样做过:
1 2 3 4 5 6 7 8 | $.ajaxSetup({ global: true, error: function(xhr, status, err) { if (xhr.status == 401) { window.location ="./index.html"; } } }); |
为401错误设置全局处理程序。 现在,我使用带有
我也在建立一个有角度的网站,我遇到了同样的全球401处理障碍。 当我看到这篇博文时,我最终使用了http拦截器。 也许你会发现它像我一样有用。
"在AngularJS(或类似的)应用程序中进行身份验证。",espeo软件
编辑:最终解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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); |
请注意,Angular 1.1.4已弃用responseInterceptors。
您可以在下面找到基于官方文档的摘录,显示实现拦截器的新方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { return { 'response': function(response) { // do something on success return response || $q.when(response); }, 'responseError': function(rejection) { // do something on error if (canRecover(rejection)) { return responseOrNewPromise; } return $q.reject(rejection); } }; }); $httpProvider.interceptors.push('myHttpInterceptor'); |
这是它在使用Coffeescript的项目中的样子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | angular.module("globalErrors", ['appStateModule']).factory"myHttpInterceptor", ($q, $log, growl) -> response: (response) -> $log.debug"success with status #{response.status}" response || $q.when response responseError: (rejection) -> $log.debug"error with status #{rejection.status} and data: #{rejection.data['message']}" switch rejection.status when 403 growl.addErrorMessage"You don't have the right to do this" when 0 growl.addErrorMessage"No connection, internet is down?" else growl.addErrorMessage"#{rejection.data['message']}" # do something on error $q.reject rejection .config ($provide, $httpProvider) -> $httpProvider.interceptors.push('myHttpInterceptor') |
使用此内容创建文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | (function(){ var httpInterceptor = function ($provide, $httpProvider) { $provide.factory('httpInterceptor', function ($q) { return { response: function (response) { return response || $q.when(response); }, responseError: function (rejection) { if(rejection.status === 401) { // you are not autorized } return $q.reject(rejection); } }; }); $httpProvider.interceptors.push('httpInterceptor'); }; angular.module("myModule").config(httpInterceptor); }()); |