Reputation: 71
I am using a shared module to provide components and services to other lazy-loaded modules in my Angular 4.2.4 app.
Everything is working well except for my injected HttpInterceptor.
If I add it to the forRoot() of the shared module then it does not get injected for my HttpCLient calls in my lazy-loaded modules.
If I leave it in the regular providers: [] section of the shared module it does get injected into my lazy-loaded modules but then it is no longer treated as a singleton and gets initialized for each module.
Does anyone know why this isn't working?
For now I am just going to allow the interceptor to have multiple instances but it isn't what I want in the end.
shared.module.ts (does not work in lazy-loaded)
@NgModule({
imports: [
CommonModule,
HttpClientModule,
],
declarations: [ ],
exports: [
CommonModule,
],
providers: [ ]
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
HttpClient,
{
provide: HTTP_INTERCEPTORS,
useClass: JwtHttpInterceptor,
multi: true
}
]
};
}
}
shared.module.ts (works in lazy-loaded but is not a singleton)
@NgModule({
imports: [
CommonModule,
HttpClientModule,
],
declarations: [ ],
exports: [
CommonModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtHttpInterceptor,
multi: true
}
]
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
HttpClient
]
};
}
}
app.module.ts
@NgModule({
declarations: [
AppComponent,
PageNotFoundComponent,
ShellComponent,
MenuComponent,
FooterComponent
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
SharedModule.forRoot()
],
providers: [ ],
bootstrap: [AppComponent]
})
export class AppModule { }
admin.module.ts (lazy-loaded module)
@NgModule({
imports: [
CommonModule,
FormsModule,
SharedModule
],
declarations: [ ],
providers: [ ]
})
export class AdminModule { }
Upvotes: 2
Views: 1022
Reputation: 9440
I got exactly the same problem with sharedmodule
and forRoot
See:
https://github.com/angular/angular/issues/20575
Try removing HttpClientModule
from your shared module
Upvotes: 1