AngularJS $ http redirect to status code

I have an angular application with many requests $http, and I want to redirect users to the login page if the server expires (get 401). Does anyone know a solution that works for everyone $httpwithout adding .error()on each $http?

+4
source share
2 answers

It would be better if you used 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);
            }
        }
    };
});
+4
source

You can use Interceptors to achieve this. Source Code Mean.js

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);
                }
            };
        }
    ]);
}
 ]);
+2
source

All Articles