user3840211 user3840211 - 5 months ago 42
AngularJS Question

AngularJS $http.interceptors.push Uncaught Error: [$injector:unpr]

I'm trying to set access-token to the header after a login is successful. I'm trying to achieve it by using interceptors but getting this error:

Uncaught Error: [$injector:unpr] Unknown provider: aProvider <- a <- TokenInterceptor <- $http <- $compile


JS

myApp.config(['$httpProvider',function ($httpProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
}]);

myApp.factory('TokenInterceptor', function ($q, $window, $location, AuthenticationService) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},

requestError: function(rejection) {
return $q.reject(rejection);
},

response: function (response) {
return response || $q.when(response);
},

//Revoke client authentication if 401 is received

responseError: function(rejection) {
console.log("Rejecton !");
console.log(rejection);

if (rejection != null && rejection.status === 401 && ($window.sessionStorage.token || AuthenticationService.isLogged)) {
console.log("Revoked !");
delete $window.sessionStorage.token;
AuthenticationService.isLogged = false;
$location.path("/admin/login");
}

return $q.reject(rejection);
}
};
});

Answer
yApp.config(['$httpProvider', function ($httpProvider) {

    var interceptor = ['$q', '$window', '$location', '$injector', function($q, $window, $location, $injector) {

        return {
            request: function (config) {
                config.headers = config.headers || {};
                if ($window.sessionStorage.token) {
                    config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
                }
                return config;
            },

            requestError: function(rejection) {
                return $q.reject(rejection);
            },

            response: function (response) {
                return response || $q.when(response);
            },

            // Revoke client authentication if 401 is received

            responseError: function(rejection) {
                console.log(rejection);
                // Dynamically get the service since they can't be injected into config
                var AuthenticationService = $injector.get('AuthenticationService');

                if (rejection != null && rejection.status === 401 && ($window.sessionStorage.token || AuthenticationService.isLogged)) {
                    delete $window.sessionStorage.token;
                    AuthenticationService.isLogged = false;
                    $location.path("/login");
                }

                return $q.reject(rejection);
            }
        };
    }];

    $httpProvider.interceptors.push(interceptor);
}]);