Search code examples
javascriptangularjsangularjs-serviceangularjs-routing

Can not push an interceptor


In angular js i have made a service that should authenticate user simply it stores a token and send it with every request so i used interceptors. her is the code of the interceptor.

app.factory('authInterceptorService',['$q', '$location', '$cookieStore', function( $q, $location, $cookieStore){
     var authInterceptorServiceFactory = {};
     var _request = function(config){
         config.headers = config.headers || {};
         var authData = $cookieStore.get('AuthorizationHeader');
         if(authData){
             config.headers.AuthorizationHeade = authData.token;
         }
         return config;
     }

     var _responseError = function(rejection) {
         if(rejection.status === 401){
             $location.path('/');
         }
         return $q.reject(rejection);
     }
     authInterceptorServiceFactory.request = _request;
     authInterceptorServiceFactory.responseError = _responseError;
     return authInterceptorServiceFactory;
}]);

the problem is when i try to add the interceptor with

app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('authInterceptorService');
});

i get Uncaught TypeError: Cannot read property 'push' of undefined from AccApp


Solution

  • The error message You mentioned suggests that $httpProvider parameter may not be injected properly. Maybe You use some kind of obfuscation that changes the variable name and breaks the injection mechanism. Please try to change:

    app.config(function ($httpProvider) { ... }); 
    

    into:

    app.config(["$httpProvider", function ($httpProvider) { ... }]);
    

    Let me know if this solves the issue.

    Edit

    After a short discussion in the comments, it seems that the error was caused by too old AngularJS version. In order to use the interceptors collection at least 1.1.4 version is required, according to this link: AngularJS $httpProvider undefined.

    Edit II

    After upgrading the version of angularjs the issue was resolved, but another issue appeared and it seems that You solved it by yourself :). As agreed, I'm adding information about it to the answer. According to our discussion, ngRoute has to be included after upgrading angularjs version, although the code worked without it in version 1.0.7.