在App Module中导入可注入值到SubModule时 [英] Access injectable value to SubModule when importing it in App Module
问题描述
好的,这是上下文...
Okay, so, here's some context...
我有一个功能模块,当它导入到app.module.ts
中时,需要将字符串值传递给它的forRoot
静态方法,如下所示:
I've got a feature module that requires a string value to be passed to its forRoot
static method when imported in app.module.ts
, like this:
@NgModule({
declarations: [ /* ... */ ],
imports: [
MyModule.forRoot('the configuration string') // <- here
],
providers: [/* ... */],
bootstrap: [ AppComponent ]
})
export class AppModule { }
但是我不想传递一个硬编码的字符串.相反,我想从应用初始化之前从后端服务器获取的配置对象中检索其值,然后在调用platformBrowserDynamic
时将其声明为extraProvider
,如下所示:
But I don't want to pass a hardcoded string. Instead I want to retrieve its value from a configuration object fetched from my backend server before app initialization, then declared as an extraProvider
when calling platformBrowserDynamic
, like this:
// main.ts
Env.getConfig$().subscribe(config => {
platformBrowserDynamic([
{ provide: AppConfig, useValue: config } // <- here
]).bootstrapModule(AppModule)
});
我知道可以使用此配置将配置注入服务中(我已经对其进行了测试):
I know that the config can be injected in a service with this configuration (I tested it):
export class AnyService {
constructor(
private config: AppConfig
) {
console.log(config); // <- Displays the expected config object
}
}
我的问题是,在AppModule
中导入MyModule
时,我想访问此注入的配置对象.像这样:
My issue is that I want to access this injected configuration object when importing MyModule
in the AppModule
. Something like:
@NgModule({
declarations: [ /* ... */ ],
imports: [
MyModule.forRoot(config.stringParamValue) // <- How to inject the AppConfig instance?
],
providers: [/* ... */],
bootstrap: [ AppComponent ]
})
export class AppModule { }
我想到了与AppModule
中的forRoot
静态方法有关的事情,该方法会使用@Inject
装饰器注入AppConfig
令牌...但是似乎有点怪异...
I thought about something involving a forRoot
static method in AppModule
, that would inject the AppConfig
token using an @Inject
decorator... but it's seems a little hacky somehow...
我还想避免将配置存储在Env.getConfig$
可观察对象的订阅回调中的某种全局变量中.
I'd also like to avoid storing my config in some kind of global variable in the subscribe callback of the Env.getConfig$
observable.
在此先感谢您的帮助!
推荐答案
尝试在模块内部定义一个注入令牌(在这种情况下为MyModule).并尝试像这样使用:
Try define an injection token inside the module (MyModule in this case). And try using like this :
// main.ts
Env.getConfig$().subscribe(config => {
platformBrowserDynamic([
{ provide: YourToken, useValue: config } // <- here
]).bootstrapModule(AppModule)
});
这篇关于在App Module中导入可注入值到SubModule时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!