如何在NestJS的@Module装饰器中使用注入的ConfigService?
解决NestJS中@Module装饰器内使用ConfigService的问题
你当前的写法行不通,因为**@Module装饰器在类实例化前就会执行**,此时constructor里的configService还没被初始化,直接用this.configService会导致未定义错误。
解决办法是使用JwtModule提供的registerAsync方法,它支持通过依赖注入获取ConfigService,具体实现如下:
修改后的完整代码
import { Module } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { JwtModule } from '@nestjs/jwt'; import { UsuarioModule } from '@api/usuario/usuario.module'; import { LocalStrategy } from './strategies'; import { AuthenticationController } from './authentication.controller'; import { AuthenticationService } from './authentication.service'; import { ConfigService } from '@nestjs/config'; @Module({ imports: [ PassportModule, JwtModule.registerAsync({ // 指定需要注入的服务 inject: [ConfigService], // 工厂函数,接收注入的ConfigService并返回JWT配置 useFactory: (configService: ConfigService) => ({ secret: configService.get<string>('JWT_SECRET'), signOptions: { expiresIn: configService.get<string>('JWT_EXPIRES_IN') ?? '1h', }, }), }), UsuarioModule, ], providers: [AuthenticationService, LocalStrategy], controllers: [AuthenticationController], exports: [AuthenticationService], }) export class AuthenticationModule {}
核心要点说明
registerAsync:NestJS提供的异步注册模块的方式,专门用于需要依赖其他服务生成配置的场景inject数组:告诉NestJS需要将哪些服务注入到useFactory函数中,这里注入ConfigServiceuseFactory:作为配置生成函数,接收注入的服务参数,返回最终的JWT配置对象
注意:需要确保你的项目已经在根模块(如AppModule)中正确导入并配置了ConfigModule,否则ConfigService无法被正常注入。
内容的提问来源于stack exchange,提问作者F. F. Knob
相关产品推荐
相关产品推荐

