【问题标题】:Angular 4.2.4 HttpInterceptor not working when used in forRoot() of shared module在共享模块的 forRoot() 中使用 Angular 4.2.4 HttpInterceptor 时不起作用
【发布时间】:2018-04-04 07:52:42
【问题描述】:

我正在使用共享模块为我的 Angular 4.2.4 应用程序中的其他延迟加载模块提供组件和服务。

除了我注入的 HttpInterceptor 之外,一切都运行良好。

如果我将它添加到共享模块的 forRoot() 中,那么它不会为我的延迟加载模块中的 HttpCLient 调用注入。

如果我将它留在共享模块的常规 providers: [] 部分中,它确实会被注入到我的延迟加载模块中,但它不再被视为单例并为每个模块进行初始化。

有谁知道为什么这不起作用?

现在我只允许拦截器有多个实例,但它最终不是我想要的。

shared.module.ts(在延迟加载中不起作用)

@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
  ],
  declarations: [ ],
  exports: [
    CommonModule,
  ],
  providers: [ ]
})  
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        HttpClient,
         {
           provide: HTTP_INTERCEPTORS,
           useClass: JwtHttpInterceptor,
           multi: true
         }
      ]
    };
  }
}

shared.module.ts(在延迟加载中工作,但不是单例)

@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
  ],
  declarations: [ ],
  exports: [
    CommonModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtHttpInterceptor,
      multi: true
    }
  ]
})  
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        HttpClient
      ]
    };
  }
}

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent,
    ShellComponent,
    MenuComponent,
    FooterComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    SharedModule.forRoot()
  ],
  providers: [ ],
  bootstrap: [AppComponent]
})
export class AppModule { }

admin.module.ts(延迟加载模块)

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    SharedModule
  ],
  declarations: [ ],
  providers: [ ]
})
export class AdminModule { }

【问题讨论】:

    标签: angular module lazy-loading


    【解决方案1】:

    sharedmoduleforRoot 遇到了完全相同的问题

    见:

    https://github.com/angular/angular/issues/20575

    尝试从您的共享模块中删除 HttpClientModule

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 2020-10-06
      相关资源
      最近更新 更多