【问题标题】:How to pass configuration into forRoot如何将配置传递给 forRoot
【发布时间】:2021-05-03 12:01:47
【问题描述】:

如何将配置对象传递给 AppModule 中的forRoot()?如果模块中没有constructor,有没有办法访问configService

config.yml:

smtp:
  host: 'smtp.host.com'
  port: 10
  secure: true
  auth:
    user: 'username'
    auth: 'password'
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    MailModule.forRoot(), // I want to pass configuration here
  ],
})
export class AppModule {}

【问题讨论】:

    标签: node.js typescript yaml config nestjs


    【解决方案1】:

    通常您需要像forRootAsync 这样的异步注册方法,但由模块创建者提供此方法。如果此方法确实存在,您可以使用工厂和inject 创建一个类类提供程序系统,Nest 可以使用as shown in the database docs 注入该系统。在不知道您正在使用哪个邮件模块的情况下,我不能说它是否支持这一点。

    如果没有这种异步注册方法,就无法在forRoot 中使用 DI。

    【讨论】:

    • 我在考虑使用 config 包,但我认为如果框架中有内置解决方案,这不是最佳实践
    【解决方案2】:

    我安装了config 包并像这样使用它:

    import * as config from 'config';
    
    const smtpConfig = config.get('smtp');
    
    @Module({
      imports: [
        MailModule.forRoot(smtpConfig),
      ],
    })
    export class AppModule {}
    

    【讨论】:

      猜你喜欢
      • 2017-09-03
      • 2019-05-19
      • 2019-12-10
      • 1970-01-01
      • 2019-07-12
      • 2012-04-03
      • 2018-09-21
      相关资源
      最近更新 更多