NestJS中父模块的注入服务

时间:2020-03-28 09:46:08

标签: dependency-injection nestjs circular-dependency

NestJS中有三个模块:EndpointModuleJWTModule和特定的端点作为模块(例如InfoModule

我的EndpointModule看起来像这样:

@Module({
    imports: [
        JWTModule.withRSAKeys(
            Path.resolveByApp('./private.key'),
            Path.resolveByApp('./public.key')
        ),
        InfoModule,
        //More Endpoints
    ],
    exports: [JWTModule]
})
export class EndpointModule {}

像这样的JWTModule:

@Module({
    providers: [JWTService],
    exports: [JWTService]
})
export class JWTModule {
    static async withRSAKeys(
        privateKeyPath: string,
        publicKeyPath: string
    ): Promise<DynamicModule> {
        return {
            module: JWTModule,
            providers: await this.createProviders(privateKeyPath, publicKeyPath)
        };
    }

如您所见,JWTModule是一个动态模块。现在,我想将导出的JWTService注入到我的端点控制器中。例如:

@Module({
    controllers: [InfoController]
})
export class InfoModule {}

@Controller()
export class InfoController {
    constructor(private jwt: JWTService){};

这不起作用。我必须将EndpointModule导入InfoModule中,但这会产生循环依赖关系。有什么办法可以避免这种情况?我应该重新订购模块吗?

1 个答案:

答案 0 :(得分:0)

您需要在JWTModule中导入InfoModule或用EndpointModule装饰Global()