创建$ http拦截器作为独立模块时Angular中的依赖性错误

Eli*_*ise 7 javascript dependency-injection angularjs angularjs-module angular-http-interceptors

这是一个工作示例,说明我如何设置一个拦截器,为每个请求附加一个身份验证令牌(这或多或少来自https://docs.angularjs.org/api/ng/service/ $ http)

angular.module("app", [])
.config(function ($httpProvider) {
  $httpProvider.interceptors.push("authInterceptor");
})
.factory("authInterceptor", function ($q) {
  return {
  // interceptor configuration here
  }
})
Run Code Online (Sandbox Code Playgroud)

config和我的run块中有很多其他的东西,它们调用和启动来自不同角度模块的服务,所以我想稍微整理一下.但是我知道在config块中依赖注入有一些非常具体的规则,我不太明白,这些都阻止我authInterceptor在一个单独的模块中定义我的工厂.由于configrun块中的其他逻辑调用应用程序中的其他模块,因此声明拦截器在那里看起来不合适.

这就是我想要做的:

angular.module("services.authInterceptor", [])
.factory("authInterceptor", function ($q) {
  return {
  // interceptor configuration here
  }
});

angular.module("app", [
 "services.authInterceptor"
]).config(function ($httpProvider, authInterceptor) {
  $httpProvider.interceptors.push("authInterceptor");
});

// Error: Unknown provider authInterceptor.
Run Code Online (Sandbox Code Playgroud)

我尝试将它注入到run块中,但我想你不允许注入$httpProvider它:

angular.module("app", [
  "services.authInterceptor"
]).run(function ($httpProvider, authInterceptor) {
  $httpProvider.interceptors.push("authInterceptor");
});

// Error: Unknown provider: $httpProviderProvider <- $httpProvider
Run Code Online (Sandbox Code Playgroud)

我应该在哪里注入模块以便$httpProvider也可以注入,我应该在哪里添加拦截器到现有模块?我的主要目标是将拦截器和其他类似服务保存在自己的自包含模块中.

编辑

我得到一个不同的错误,当我声明一个provider而不是factory(由于某种原因我总是认为这些是可以互换的)时,似乎让我更接近:

angular.module("services.authInterceptor")
.provider("authInterceptor", function ($q) {
  return {}
})

// Error: Unknown provider: $q
Run Code Online (Sandbox Code Playgroud)

所以现在它成功地注入authInterceptor了我的config块,但在尝试查找时失败了$q.

tas*_*ATT 10

在配置阶段,只能注入提供者和常量.这是为了防止服务在完全配置之前进行实例化.

这就是您按名称注册拦截器(将名称作为字符串推入$httpProvider.interceptors数组)的原因.它们将在运行时稍后解析.

这正是您在工作示例中所做的,以及您在第二步中需要做的事情,即使拦截器在另一个模块中:

angular.module("services.authInterceptor", [])
.factory("authInterceptor", function ($q) {
  return {
  // interceptor configuration here
  }
});

angular.module("app", ["services.authInterceptor"])
.config(function ($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
});
Run Code Online (Sandbox Code Playgroud)

演示: http ://plnkr.co/edit/A8SgJ87GOBk6mpXsoFuZ?p =preview