I have a angular application with many $http
request and i want redirect the users on the login page if the server session expires (get 401). Does anyone know a solution witch works for all $http
without adding .error()
on every $http
?
Asked
Active
Viewed 3,221 times
4

Muhammad Reda
- 26,379
- 14
- 93
- 105

Christoph
- 1,993
- 1
- 25
- 33
2 Answers
4
It would be better if you could use an http interceptor to redirect all detected 401 errors.
// 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);
}
}
};
});

Muhammad Reda
- 26,379
- 14
- 93
- 105
-
1Does this really work? It doesn't seem to actually perform a full page refresh. https://docs.angularjs.org/guide/$location also states: "It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, `$window.location.href`." – comecme Apr 17 '15 at 06:55
2
You can use Interceptors to achieve this. From Mean.js source code
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);
}
};
}
]);
}
]);

Subin Sebastian
- 10,870
- 3
- 37
- 42