Angular 4.3 Interceptors for Lazy Loaded Modules Angular 4.3 Interceptors for Lazy Loaded Modules angular angular

Angular 4.3 Interceptors for Lazy Loaded Modules


You don't have to create a provider for your interceptor. You should export your CoreModule with forRoot():

@NgModule({  imports: [    CommonModule,    HttpClientModule,    TranslateModule.forRoot({      loader: {        provide: TranslateLoader,        useFactory: HttpLoaderFactory,        deps: [HttpClient]      }    }),    RouterModule.forRoot(      [],      {enableTracing: true}    ),  ],  declarations: [],  providers: [DatePipe]})export class CoreModule {  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {    if (parentModule) {      throw new Error(        'CoreModule is already loaded. Import it in the AppModule only');    }  }  static forRoot(): ModuleWithProviders {    return {      ngModule: CoreModule,      providers: [        {provide: 'Window', useValue: window},        {provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true},        SORT_TYPES_PROVIDER,        ApiService,        AnimationService,        BillingService,        UserService,        ...      ]    };  }}

Then import it in your AppModule and forget about CoreModule imports at all. This is only one place it has to be explicitly used. All your lazy loaded modules will take your services etc by DI.

@NgModule({  declarations: [    AppComponent  ],  imports: [    BrowserModule,    SharedModule,    CoreModule.forRoot(),    FeaturesModule,    PublicModule,    RouterModule.forRoot([])  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule {}

Also you don't need to create a separate routing module for each module. Just export what RouterModule.forChild returns and use it in imports of your module that needs it.

export const publicRouting: ModuleWithProviders = RouterModule.forChild([  {    path: 'login',    pathMatch: 'full',    component: SignInComponent,    data: {      breadcrumb: 'LGN_TL'    },    canActivate: [AuthenticatedGuard]  },  {    path: '',    component: GlobalComponent,    loadChildren: '../protected/protected.module#ProtectedModule',    canLoad: [AuthCanLoadGuard]  },  {path: '**', component: PageNotFoundComponent}]);

UPD. suggestion for routing not a styleguide. Use RoutingModule as before (https://angular.io/guide/styleguide#angular-ngmodule-names)