Reputation: 330
I'm trying to implement an http interceptor using the new HttpClient in Angular 4.3, but I keep getting the error:
ERROR Error: Uncaught (in promise): Error: No provider for AuthInterceptor!
This is what I have in my 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 },
]
};
I've looked into all the articles with the error "No provider for CustomService", and they all refer to making sure that the service is added to the providers list in app.module which I think I've done.
Does anyone have any other ideas?
Thanks.
Upvotes: 1
Views: 4404
Reputation: 31803
TL;DR: change useExisting
to useClass
or add AuthInterceptor
to your providers
array if you want to inject it somewhere else explicitly.
There is likely an error in your provider configuration. Specifically you have registered your AuthInterceptor
with the useExisting
provider option.
What this does is register an alias for another, existing dependency injection provider under a new token.
The purpose of that would be to make a service which is already provided as AuthInterceptor
available for injection via the token HTTP_INTERCEPTORS
.
Therefore, unless some other ngModule
imported by your application* is already providing something under the token AuthInterceptor
, it will fail.
To resolve the problem at hand, change useExisting
to useClass
, if AuthInterceptor
is a class, otherwise change it to useValue
or useFactory
as needed.
Another option would be to add AuthInterceptor
to your providers
property you would do this if you want to inject it directly somewhere else.
*
Note that all providers that are imported via eagerly loaded ngModules
are merged into a shared, global dependency injection container.
Upvotes: 4