Angular 4.3 Interceptors for Lazy Loaded Modules

前端 未结 1 1599
迷失自我
迷失自我 2020-12-19 01:01

What is the best practice to use core module service in lazy loaded feature module and feature child modules.
As per Angular style guide I have the following



        
相关标签:
1条回答
  • 2020-12-19 01:59

    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)

    0 讨论(0)
提交回复
热议问题