Angular:从惰性功能模块添加多提供者

Fel*_*lix 5 typescript angular-module angular

我有一个 ErrorModule (eager) 配置如下:

export const CONFIG = new InjectionToken<ErrorConfig[]>('Module errors configuration.');


@NgModule({
  imports: [... ]
})
export class ErrorModule {
  static forRoot(config: ErrorConfig): ModuleWithProviders {
    return {
      ngModule: ErrorModule,
      providers: [
        ErrorService,
        { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
        { provide: CONFIG, useValue: config, multi: true }
      ]
    };
  }

  static forChild(config: ErrorConfig): ModuleWithProviders {
    return {
      ngModule: ErrorModule,
      providers: [
        { provide: CONFIG, useValue: config, multi: true }
      ]
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

然后导入核心模块ErrorModule如下:

@NgModule({
  imports: [
    ErrorModule.forRoot(ERROR_CONFIG)
  ], ...
Run Code Online (Sandbox Code Playgroud)

延迟加载子功能模块:

@NgModule({
  imports: [
    ErrorModule.forChild(ERROR_CONFIG_CHILD)
  ], ...
Run Code Online (Sandbox Code Playgroud)

我想看到这两种配置ERROR_CONFIGERROR_CONFIG_CHILD注入到ErrorServiceErrorModule 中定义

@Injectable
export class ErrorService {
    constructor(@Inject(CONFIG) private readonly errorConfigs: ErrorConfig[])
}
Run Code Online (Sandbox Code Playgroud)

但服务errorConfigs(在构造函数中)仅包含在函数中定义CONFIG的(具有一个元素的数组)。core.moduleforRoot()

惰性功能模块已加载并初始化并被ErrorModule.forChild(...)调用

ErrorService当只有核心模块的注入令牌可用时,已经及时构建了,这是有道理的CONFIG——功能模块尚未加载。

我还尝试在构造函数之外导入CONFIGusing Angular (方法),结果是相同的。InjectorErrorService

const configs: any[] = injector.get(CONFIG); // returns only root CONFIG
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:是否可以以某种方式访问​​应用程序模块中的惰性模块提供的提供程序?(在应用程序的根注入器中访问它?)

Fel*_*lix 2

我最终得到了一个解决方案,它使用ErrorService定义在初始化CoreModule时注册配置:FeatureModule

import { ErrorService } from '@core/error.service';

@NgModule({
    imports: [ CommonModule, ForFeatureModule, TranslateModule.forChild() ],
    declarations: [FeatureModule],
    providers: []
})
export class FeatureModule {
    constructor(
        private readonly translate: TranslateService, private readonly errorService: ErrorService) {
        translate.setTranslation('cz', i18n, true);

        // --- HERE --- errorService configures global error configuration
        errorService.addErrorMappings('FEATURE1', ERROR_MAPPING);
    }
}
Run Code Online (Sandbox Code Playgroud)