【问题标题】:Access injectable value to SubModule when importing it in App Module在 App Module 中导入 SubModule 时访问可注入值
【发布时间】: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


    【解决方案1】:

    尝试在模块内定义一个注入令牌(本例中为 MyModule)。并尝试像这样使用:

        // main.ts
    Env.getConfig$().subscribe(config => {
        platformBrowserDynamic([
          { provide: YourToken, useValue: config } // <- here
        ]).bootstrapModule(AppModule)
    });
    

    api doc sample implementation

    【讨论】:

    • 天啊!很简单!我当然可以这样做。事实上,我已经在 MyModule 中定义了一个注入令牌;它由forRoot 方法提供,其值作为参数传递。实施您的建议几乎没有什么可做的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2012-12-28
    相关资源
    最近更新 更多