将$ http注入工厂时,$ httpProvider拦截器无法正常工作

时间:2014-07-28 12:25:17

标签: angularjs angularjs-service

我有一个名为'api'的服务,注册的内容如下:

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

...并且$ http正在其他地方进行定制:

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');
  });

当我直接将$http注入控制器时,拦截器正在工作,但是当我在控制器中使用api服务时,$http自定义项无效。看起来Angular没有按照我创建的工厂要求的点添加截距。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

问题是基于错误的前提。拦截器实际上工作,我只是使用错误的钩点。我试图拦截responseError属性本身的错误,而不是自定义拦截器对象的response属性。这就是我认为拦截器根本不起作用的原因。

这个问题确实不存在。提供商的拦截器即使在工厂也能正常工作。

答案 1 :(得分:0)

您可以尝试在配置中设置httpInterceptor变量而不是将其作为工厂:

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);
  });

请注意,我还将$httpProvider.interceptors更改为$httpProvider.responseInterceptors,而传递给push()的参数不是字符串。

如果有帮助,请告诉我。

修改

您还可以考虑使用此插件:https://github.com/witoldsz/angular-http-auth。拦截后它具有这个很酷的功能:"然后authService将重试之前因HTTP 401响应而失败的所有请求。"