错误:没有AuthInterceptor的提供者

时间:2017-07-17 01:53:46

标签: angular

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

  

错误错误:未捕获(承诺):错误:没有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 for CustomService”,他们都参考确保将服务添加到app.module中的提供者列表中,我认为我已经完成了。< / p>

有没有人有其他想法?

感谢。

1 个答案:

答案 0 :(得分:2)

TL; DR:useExisting更改为useClass AuthInterceptor添加到您的providers媒体资源中想直接把它注射到其他地方。

您的提供商配置中可能存在错误。具体而言,您已使用AuthInterceptor提供商选项注册了useExisting

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

这样做的目的是通过令牌AuthInterceptor创建一个已经作为HTTP_INTERCEPTORS提供的服务。

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

要解决手头的问题,请将useExisting更改为useClass,如果AuthInterceptor是一个类,则根据需要将其更改为useValueuseFactory 。 另一种选择是将AuthInterceptor添加到您要执行此操作的providers属性中,如果您想将其直接注入其他位置。

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

相关问题