Angular中如何在Promise返回后动态导入依赖配置的模块?
Angular运行时加载配置后导入依赖模块的解决方案
问题背景
我需要通过Promise获取运行时配置(而非静态环境变量),必须等配置加载完成后再启动应用,当前应用启动的实现如下:
export class AppModule { constructor(private configService: ConfigService) {} ngDoBootstrap(app: ApplicationRef) { this.configService.init().then((config) => { app.bootstrap(AppComponent); }); } }
但存在一个问题:@NgModule中导入的内部库模块StylesComponentsModule依赖该运行时配置,旧实现是用静态环境对象通过StylesComponentsModule.forRoot(configuration)初始化,现在要改为使用运行时加载的配置,无法在@NgModule的imports数组中直接配置(因为配置还未加载)。尝试过类似ngDoImport的自定义逻辑,但无效。
可行解决方案
通过在ngDoBootstrap中先加载配置,再动态导入目标模块并完成初始化,最后启动应用,实现代码如下:
export class AppModule { constructor(private configService: ConfigService) {} ngDoBootstrap(app: ApplicationRef) { this.configService.init().then((config) => { // 动态导入StylesComponentsModule并传入运行时配置初始化 import('module/path') // 替换为实际模块路径 .then(module => module.StylesComponentsModule.forRoot(config)); app.bootstrap(AppComponent); }); } }
注意:动态导入模块时,需确保路径正确,且模块导出的
StylesComponentsModule能通过forRoot正确接收配置参数。
内容的提问来源于stack exchange,提问作者AlleXyS
相关产品推荐
相关产品推荐

