What is the easiest way to detect $http
errors from the server and delete the token if ANY of the calls cause a 401 error? For example, if a session expires while the user is not using the app, when they return to the web app the token is no longer valid. If I send back a 401 error during an API call I need to notice this and make the user log back in.
Currently, in the Chrome Developer Tools, I can see the 401 error but Satellizer does not delete the token (thought it did at one time).
I tried creating an httpInterceptor, but received Circular Dependency error:
apiLogoutInterceptor.$inject = ['$q', '$auth'];
function apiLogoutInterceptor ($q, $auth) {
var service = this;
service.responseError = function (response) {
if (response.status == 401) {
$auth.removeToken();
window.location = '/login';
}
return $q.reject(response);
};
}
configureApiLogout.$inject = ['$httpProvider'];
function configureApiLogout ($httpProvider) {
$httpProvider.interceptors.push('apiLogoutInterceptor');
}
You can workaround the cyclic dependency by just injecting the
$injector
service and fetching your required dependencies manually. For an example, see this post: AngularJS: Injecting service into a HTTP interceptor (Circular dependency)Additionally, I don't see any reason for using
var service = this
as it is enough to return a simple object containing the handler method for theresponseError
key like this: