Когда мой сайт был на 100% jQuery, я использовал это:
$.ajaxSetup({
global: true,
error: function(xhr, status, err) {
if (xhr.status == 401) {
window.location = "./index.html";
}
}
});
чтобы установить глобальный обработчик ошибок 401. Теперь я использую angularjs с $resource
и $http
для выполнения моих (REST) запросов на сервер. Есть ли способ аналогично установить глобальный обработчик ошибок с angular?
Я также создаю веб-сайт с angular, и я столкнулся с тем же препятствием для глобальной обработки 401. Я закончил использование перехватчика http, когда я столкнулся с этим сообщением в блоге. Возможно, вы найдете его полезным, как я.
"Аутентификация в приложении AngularJS (или аналогичном)" ., espeo software
EDIT: окончательное решение
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);
Обратите внимание, что responseInterceptors устарели с помощью Angular 1.1.4. Ниже вы можете найти отрывок, основанный на официальных документах , в котором показан новый способ реализации перехватчиков.
$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:
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')
responseError
, у rejection
есть все, что вам нужно.
Создайте файл <script type="text/javascript" src="../js/config/httpInterceptor.js" ></script>
с этим контентом:
(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);
}());