$httpProvider interceptor not working when $http is injected into a factory

I have a service called 'api', registered something like this:

angular
  .module('myApp')
  .factory('api', ['$http', function ($http) {
    // do stuff with $http.get() etc here.
  }]);

... and $http is being customized like this elsewhere:

angular
  .module('myApp')
  .factory('httpInterceptor', ['$rootScope', function ($rootScope) {
    // do stuff to intercept http requests and auth things here
  }]);

angular
  .module('myApp')
  .config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
  });

The interceptors are working when I directly inject $http into a controller, but when I use the api service in my controller, the $http customizations are not working. Looks like Angular does not add the intercepts by the point it's required by the factory I created.

How do I solve this?


The question was based on a wrong premise. The interceptors are in fact working, I was just using the wrong hook point. Instead of customizing the responseError property of the interceptor object, I was trying to intercept errors from the response property itself. This is why I thought the interceptors weren't working at all.

This problem does not really exist. The provider's interceptors are working correctly even in a factory.


You can try to make the httpInterceptor a variable inside the config instead of making it a factory:

angular
  .module('myApp')
  .config(function ($httpProvider) {

    var httpInterceptor = ['$rootScope', 
      function($rootScope) {
        // do stuff to intercept http requests and auth things here
      }
    ];

    $httpProvider.responseInterceptors.push(httpInterceptor);
  });

Please note that I've also changed $httpProvider.interceptors to $httpProvider.responseInterceptors and the parameter passed to push() is not a string.

Let me know if that helps.

EDIT:

You can also consider using this plugin: https://github.com/witoldsz/angular-http-auth. It has this cool feature after the interception: "The authService will then retry all the requests previously failed due to HTTP 401 response."

链接地址: http://www.djcxy.com/p/77606.html

上一篇: angularjs视图仅在硬刷新上加载,而不在重定向上加载

下一篇: 当$ http被注入工厂时,$ httpProvider拦截器不工作