在App Module中导入可注入值到SubModule时 [英] Access injectable value to SubModule when importing it in App Module

查看:130
本文介绍了在App Module中导入可注入值到SubModule时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是上下文...

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 MyModulein 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)
});

api文档 示例实现

这篇关于在App Module中导入可注入值到SubModule时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆