【发布时间】:2019-11-11 22:10:21
【问题描述】:
好的,所以,这里有一些上下文......
我有一个功能模块,当导入app.module.ts 时,需要将字符串值传递给它的forRoot 静态方法,如下所示:
@NgModule({
declarations: [ /* ... */ ],
imports: [
MyModule.forRoot('the configuration string') // <- here
],
providers: [/* ... */],
bootstrap: [ AppComponent ]
})
export class AppModule { }
但我不想传递硬编码的字符串。相反,我想在应用初始化之前从后端服务器获取的配置对象中检索其值,然后在调用platformBrowserDynamic 时声明为extraProvider,如下所示:
// main.ts
Env.getConfig$().subscribe(config => {
platformBrowserDynamic([
{ provide: AppConfig, useValue: config } // <- here
]).bootstrapModule(AppModule)
});
我知道这个配置可以注入到服务中(我测试过):
export class AnyService {
constructor(
private config: AppConfig
) {
console.log(config); // <- Displays the expected config object
}
}
我的问题是我想在AppModule 中导入MyModule 时访问这个注入的配置对象。比如:
@NgModule({
declarations: [ /* ... */ ],
imports: [
MyModule.forRoot(config.stringParamValue) // <- How to inject the AppConfig instance?
],
providers: [/* ... */],
bootstrap: [ AppComponent ]
})
export class AppModule { }
我想到了一些涉及AppModule 中的forRoot 静态方法的事情,它会使用@Inject 装饰器注入AppConfig 令牌......但它似乎有点hacky......
我还想避免将我的配置存储在Env.getConfig$ observable 的订阅回调中的某种全局变量中。
提前感谢您的帮助!
【问题讨论】:
标签: angular