How to import Angular HTTP interceptor only for Child module

南笙酒味 提交于 2021-01-28 05:30:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!