为什么必须为每个惰性模块提供HTTP_INTERCEPTORS

时间:2018-11-28 06:53:41

标签: angular angular7

我在AuthInterceptor提供了AppModule。它在AppModule可以正常工作,但是在LazyModule上却无法正常工作。我必须提供此interceptor才能使所有惰性模块正常工作。

我真的很惊讶为什么会这样。我在其他项目中实现了同样的功能,但是效果很好,但是在这里我必须在每个模块中提供。不知道是什么原因引起的。

AppModule

@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        HttpClientModule,
        AppRoutingModule,

        //NgbModule.forRoot(),
        ThemeModule.forRoot(),
        CoreModule.forRoot(),
    ],
    bootstrap: [AppComponent],
    providers: [
        {provide: APP_BASE_HREF, useValue: '/'},
        {provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true},
        AuthGuard,
        {
            provide: NbRoleProvider,
            useClass: RoleProvider,
        },
        ZtLoaderService
    ],
})
export class AppModule {
}

AppRoutingModule

const routes: Routes = [
    {
        path: 'pages',
        canActivate: [AuthGuard], // here we tell Angular to check the access with our AuthGuard
        loadChildren: 'app/pages/pages.module#PagesModule'
    },
    {path: '', redirectTo: 'pages', pathMatch: 'full'},
    {path: '**', redirectTo: 'pages'},
];

const config: ExtraOptions = {
    useHash: true,
};

@NgModule({
    imports: [RouterModule.forRoot(routes, config)],
    exports: [RouterModule],
})
export class AppRoutingModule {
}

PagesModule

@NgModule({
  imports: [
    PagesRoutingModule,
    ThemeModule,
    Dashboard2Module
  ],
  declarations: [
    PagesComponent,
  ],
})
export class PagesModule {
}

PagesRoutingModule

const routes: Routes = [{
    path: '',
    component: PagesComponent,
    children: [{
        path: 'dashboard',
        component: DashboardComponent2,
    },
    {
        path: 'profile',
        loadChildren: './profile/profile.module#ProfileModule',

    }],
}];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule],
})
export class PagesRoutingModule {
}

ProfileModule

@NgModule({
    imports: [
        ThemeModule,
        ProfileRoutingModule,
        Ng2SmartTableModule,

    ],
    declarations: [
        ...routedComponents,
        ...components

    ],
     providers: [{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}],   //<--- Interceptor is provided here. Could be avoided.
})
export class ProfileModule {}

0 个答案:

没有答案