我有一个Angular应用程序,其中有许多$http
请求,如果服务器会话过期(获取401),我想将用户重定向到登录页面。是否有人知道适用于所有$http
的解决方案,而无需在每个$http
上添加.error()
?
我有一个Angular应用程序,其中有许多$http
请求,如果服务器会话过期(获取401),我想将用户重定向到登录页面。是否有人知道适用于所有$http
的解决方案,而无需在每个$http
上添加.error()
?
如果您能使用HTTP拦截器重定向所有检测到的401错误,那将更好。
// add an http interceptor via app.config
app.config(function($$httpProvider) {
$httpProvider.interceptors.push('my401Detector');
});
// interceptor logic.
app.factory('my401Detector', function($location, $q) {
return {
responseError: function(response) {
if(response.status === 401) {
$location.path('/login');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
});
angular.module('users').config(['$httpProvider',
function($httpProvider) {
// Set the httpProvider "not authorized" interceptor
$httpProvider.interceptors.push(['$q', '$location', 'Authentication',
function($q, $location, Authentication) {
return {
responseError: function(rejection) {
switch (rejection.status) {
case 401:
// Deauthenticate the global user
Authentication.user = null;
// Redirect to signin page
$location.path('signin');
break;
case 403:
// Add unauthorized behaviour
break;
}
return $q.reject(rejection);
}
};
}
]);
}
]);
$window.location.href
。” - comecme