【问题标题】:Error: No provider for AuthInterceptor错误:没有 AuthInterceptor 的提供者
【发布时间】:2017-07-17 01:53:45
【问题描述】:

我正在尝试使用 Angular 4.3 中的新 HttpClient 实现一个 http 拦截器,但我不断收到错误消息:

ERROR 错误:未捕获(承诺中):错误:没有 AuthInterceptor 的提供者!

这就是我的 app.module.ts 中的内容:

@NgModule({
bootstrap: [AppComponent],
declarations: [
    AppComponent,
    LoginComponent,
    NotFoundComponent
],
imports: [
    RouterModule.forRoot([
        { path: "", redirectTo: "login", pathMatch: "full" },
        { path: "login", component: LoginComponent },
        { path: "**", component: NotFoundComponent }
    ]),

    NgbModule.forRoot(),
    BrowserAnimationsModule,
    HttpClientModule,
],
providers: [
    AuthenticationService,
    { provide: HTTP_INTERCEPTORS, useExisting: AuthInterceptor, multi: true },
]
};

我查看了所有带有错误“没有 CustomService 提供者”的文章,它们都提到确保将服务添加到 app.module 中的提供者列表中,我认为我已经完成了。

还有人有其他想法吗?

谢谢。

【问题讨论】:

  • 你为什么使用useExisting?那是为了给现有的依赖令牌起别名。除非某些东西已经在令牌 AuthInterceptor 下提供了某些东西,否则它将失败。尝试将 AuthInterceptor 添加到您的 providers 属性中。
  • 啊,你是对的。我遵循了关于实现拦截器的教程,但没有意识到 useExisting 意味着它必须已经存在。如果您提交评论作为问题的答案,我很乐意将其标记为正确答案。

标签: angular


【解决方案1】:

TL;DR:useExisting 更改为 useClass 如果您想明确地在其他地方注入 AuthInterceptor 到您的 providers 数组中。

您的提供程序配置中可能存在错误。具体来说,您已经使用useExisting 提供程序选项注册了您的AuthInterceptor

这样做是在新令牌下为另一个现有的依赖注入提供程序注册一个别名。

这样做的目的是使已经以AuthInterceptor 提供的服务可通过令牌HTTP_INTERCEPTORS 进行注入。

因此,除非您的应用程序* 导入的其他ngModule 已经在令牌AuthInterceptor 下提供了某些内容,否则它将失败。

要解决手头的问题,请将useExisting 更改为useClass,如果AuthInterceptor 是一个类,否则根据需要将其更改为useValueuseFactory。 另一种选择是将AuthInterceptor 添加到您的providers 属性中,如果您想直接在其他地方注入它,您可以这样做。

* 请注意,通过 急切 加载的 ngModules 导入的所有提供程序都合并到一个共享的全局依赖注入容器中。

【讨论】:

  • @LamboJayapalan 我在这个答案中犯了一个小错误,我刚刚更新了它。
猜你喜欢
  • 2018-04-24
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 2017-11-24
  • 2018-05-22
  • 1970-01-01
相关资源
最近更新 更多