问题
I have imported HttpClientModule in AppModule.
import { HttpClientModule } from '@angular/common/http';
export const AppRoutes: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{
path: 'account',
loadChildren: './auth/auth.module#AuthModule'
},
{
path: 'dashboard',
loadChildren: './content/content.module#ContentModule'
}
];
Once I launch site, it will redirect to dashboard module(Lazy loaded module) where i added http interceptor.
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpInterceptorService } from '../services/http-interceptor.service';
@NgModule({
providers : [
{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
]
})
But it doesn't working. Can anyone help me?
回答1:
Http interceptor is just a service there won't be any difference in injecting it on any modules - just do the same in AppModule
that will help you to work - if in case you have the same problem you can try injecting like below on your shared module
The common pattern to achieve that is not to expose providers directly on the @NgModule
declaration but in a static forRoot function like that:
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
]
};
}
}
You can then import your SharedModule
on AppModule
like SharedModule.forRoot()
Hope this works - Happy coding
来源:https://stackoverflow.com/questions/53305685/how-to-import-angular-http-interceptor-only-for-child-module