App.Module.ts 有没有办法使用 configService?

Is there a way to use configService in App.Module.ts?

我正在使用 NestJs 构建 RESTful 服务,我已经按照 example 为不同的环境构建配置。它适用于大多数代码。但是我想知道我是否可以在 app.module.ts?

中使用它
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mongodb',
      host: `${config.get('mongo_url') || 'localhost'}`,
      port: 27017,
      username: 'a',
      password: 'b',
      database: 'my_db',
      entities: [__dirname + '/MyApp/*.Entity{.ts,.js}'],
      synchronize: true}),
    MyModule,
    ConfigModule,
  ],
  controllers: [],
  providers: [MyService],
})
export class AppModule { }

如您所见,我确实想将 MongoDb Url 信息移到代码之外,并且我正在考虑利用 .env 文件。但是尝试了一番,好像还是不行。

当然可以用${process.env.MONGODB_URL || 'localhost'}代替,设置环境变量。我仍然很好奇我是否能让 configService 工作。

您必须使用 dynamic import(参见 异步配置)。使用它,您可以注入依赖项并将它们用于初始化:

TypeOrmModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (configService: ConfigService) => ({
    type: 'mongodb',
    host: configService.databaseHost,
    port: configService.databasePort,
    username: configService.databaseUsername,
    password: configService.databasePassword,
    database: configService.databaseName,
    entities: [__dirname + '/**/*.entity{.ts,.js}'],
    synchronize: true,
  }),
  inject: [ConfigService],
}),