nestjs依赖注入失败的问题
发布于 7 年前 作者 PanZhangOne 3963 次预览 最后一次回复是 7 年前 来自 问答
在使用nestjs的时候遇到无法实现依赖注入的问题。
使用中文文档的ModuleRef方式来实现authService对userService的依赖注入,但是报"Cannot read property 'check' of null"错误。
以下是部分代码。
auth.module.ts
@Module({
imports: [TypeOrmModule.forFeature([AuthEntity])],
components: [AuthService],
exports: [AuthService],
})
export class AuthModule{}
user.service.ts
@Component()
export class UserService implements OnModuleInit {
private authService: AuthService;
constructor(@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
private readonly moduleRef: ModuleRef) {
}
async test(user: UserEntity): Promise<UserEntity> {
// "Cannot read property 'check' of null"
const is = await this.authService.check(user);
}
onModuleInit() {
this.authService = this.moduleRef.get<AuthService>(AuthService);
}
}
版本信息
"@nestjs/common": "^4.5.9",
"@nestjs/core": "^4.5.10",
2 回复
moduleRef只能是自己module的components里面找而且你没初始化过 怎么用
@5196666qwe 所噶,非常感谢,但是老哥,不是很懂这段代码啊