简体   繁体   中英

Error while trying to use angularjs interceptors Uncaught getting Cannot call method 'push' of undefined

I am using Angularjs 1.2.0rc1. The all day i have been trying to get angular interceptors to work. I have narrowed down the problem to be that $httpProvider.interceptors.push seem to be undefined, I have no clue why, Everything else is working fine.

The following is sample code:

services.factory('testInterceptor', function ($q) {
return {    
  'response': function(response) {
    console.log(response);
    return response || $q.when(response);
  },     
  'responseError': function(rejection) {
    console.log(rejection);
    return $q.reject(rejection);
  }
};
});

in the module.config I have the following code.

$httpProvider.interceptors.push('testInterceptor');

if I delete the above code, the application works fine, however if its present , i keep on getting this error on my console

"Uncaught TypeError: Cannot call method 'push' of undefined from myModule."

myModule is the name of the module.

Please do note that, from my investigation "$httpProvider.interceptors" seems to be undefined, i have no clue as to why it is, any insight would be helpful.

I appreciate any assistance/hints your might have.

Does your config looks like below?

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

I use the interceptor, but inline leading to this code:

myModule.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push(function($q) {
    return {
        // optional method
        'request': function(config) {
            return config || $q.when(config);
        },

        // optional method
        'requestError': function(rejection) {
            return $q.reject(rejection);
        },

        // optional method
        'response': function(response) {
            return response || $q.when(response);
        },

        // optional method
        'responseError': function(rejection) {
            return $q.reject(rejection);
        }
    }
  })
}]);

But i never seem to get into requestError or responseError, even if the server throws a 500 error, but that looks like another problem. Hope this code sample helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM