CNode

nestjs依赖注入失败的问题

问答
PPanZhangOne发布于8 年前最后回复8 年前2 回复4134 浏览0 收藏

在使用nestjs的时候遇到无法实现依赖注入的问题。

使用中文文档的ModuleRef 方式来实现authServiceuserService的依赖注入,但是报 "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)

Y
yviscool#1·8 年前

moduleRef 只能是自己 modulecomponents 里面找

 class {
      public readonly components = components;

      public get<T>(type: OpaqueToken): T {
        const name = isFunction(type) ? (type as Metatype<any>).name : type;
        const exists = this.components.has(name);

        return exists ? (this.components.get(name).instance as T) : null;
      }
    };

而且你没初始化过 怎么用

P
PanZhangOne#2·8 年前
引用 yviscoolmoduleRef 只能是自己 module 的 components 里面找 而且你没初始化过 怎么用

@5196666qwe 所噶,非常感谢,但是老哥,不是很懂这段代码啊

参与回复
登录后即可参与回复。登录