同一模块内TokenValidatorService注入AuthService后为undefined问题
问题分析与解决:TokenValidatorService在AuthService中注入为undefined
核心问题
- 模块配置错误:
auth.module.ts中把服务类直接放到了imports数组——NestJS里imports用于导入其他模块,服务类必须放在providers数组中才能被DI容器管理。 - 缺少注入装饰器:
AuthService和TokenValidatorService都未添加@Injectable()装饰器,NestJS依赖注入系统无法识别这些类,导致实例注入失败。
修正步骤
1. 为服务添加@Injectable()装饰器
修改auth/services/token-validator.service.ts:
import { Injectable } from '@nestjs/common'; @Injectable() export class TokenValidatorService { constructor() {} async validate(token: string, url: string): Promise<boolean> { return false; } }
修改auth/services/auth.service.ts:
import { Injectable } from '@nestjs/common'; import { TokenValidatorService } from "./token-validator.service"; console.log('Init AuthService ' + TokenValidatorService); @Injectable() export class AuthService { private userPool: UserPool; constructor( private readonly tokenValidatorService: TokenValidatorService ) { console.log(tokenValidatorService); this.userPool = new UserPool('xxx'); } async isAuthorizated(token: string) { console.log(this.tokenValidatorService); await this.tokenValidatorService.validate(token, ''); } }
2. 修正AuthModule配置
将服务移至providers数组,并导出需要给其他模块使用的服务:
import { Module } from '@nestjs/common'; import { HttpModule } from '@nestjs/axios'; import { AuthService } from './services/auth.service'; import { TokenValidatorService } from './services/token-validator.service'; @Module({ imports: [ HttpModule.registerAsync({ useFactory: () => ({ timeout: 5000, maxRedirects: 3 }), }) ], providers: [AuthService, TokenValidatorService], exports: [AuthService, TokenValidatorService] // 导出供users模块使用 }) export class AuthModule {}
额外说明
users控制器能临时使用TokenValidatorService是因为NestJS会尝试直接实例化未被容器管理的类,但这不符合DI规范。修正后所有服务由容器统一管理,注入逻辑即可正常工作。
内容的提问来源于stack exchange,提问作者novac
相关产品推荐
相关产品推荐

