【发布时间】:2017-06-23 07:30:39
【问题描述】:
我在使用 Angular 4 时遇到了一点引导问题。 我有一个配置文件 (json),我在应用程序启动时从服务器加载(另请参阅 here)。到目前为止,这有效。
现在我有一个dependency,它需要在 forRoot 方法中传递配置值。实现如下所示:
static forRoot(config: AppInsightsConfig): ModuleWithProviders {
return {
ngModule: ApplicationInsightsModule,
providers: [
{ provide: AppInsightsConfig, useValue: config }
]
};
}
我的想法是在没有 forRoot() 的情况下导入模块,但在加载配置(来自服务器)之后提供 AppInsightsConfig。
@NgModule({
bootstrap: sharedConfig.bootstrap,
declarations: [...sharedConfig.declarations],
imports: [
BrowserModule,
FormsModule,
HttpModule,
ApplicationInsightsModule,
...sharedConfig.imports
],
providers: [
{ provide: 'ORIGIN_URL', useValue: location.origin },
{ provide:
APP_INITIALIZER,
useFactory: (configService: ConfigService) => () => configService.load(),
deps: [ConfigService], multi: true
},
{ provide:
AppInsightsConfig,
useFactory: (configService: ConfigService) => {
// outputs undefined, expected it to have the config
console.log(configService.config);
return { instrumentationKey: 'key from config' }
},
// My idea was, if I add APP_INITIALIZER as dependency,
// the config would have been loaded, but this isn't the case.
deps: [APP_INITIALIZER, ConfigService]
},
AppInsightsService
]
})
我的配置加载后如何提供 AppInsightsConfig 或其他服务?
【问题讨论】:
-
您是在使用路由还是在自己的模块上实现了
forRoot? -
@Maximus 不,forRoot 旨在从该第 3 方模块的模块中调用。 see this source file
-
你不能那样做。而且根据我对上面代码的理解,你不需要。
configService没有代码,但你可以在AppInsightsConfig中链接一个 Promise 并修补返回的对象。 AppInsightsConfig 最初不会有instrumentationKey,但会在应用程序初始化后拥有它。deps: [APP_INITIALIZER,会搞砸 DI 但无济于事。 -
@estus 感谢您的提示。 DI 真的搞砸了,还有很多问题。
标签: angular typescript