【问题标题】:Nest TypeScript error: Nest can't resolve dependencies of the ChildServiceNest TypeScript 错误:Nest 无法解析 ChildService 的依赖项
【发布时间】:2023-02-04 23:50:41
【问题描述】:

我有一个类结构是这样的:

我在 libs/childmodule/src/child.module.ts 中有一个 ChildModule。我有一个 taconfig.json,它映射到 @app

然后我有一个 parentModule,我试图在其中导入 ChildModule。代码:

ChildModule:


import { Module } from '@nestjs/common';
import { ChildService } from './child.service';
import { LoggerModule } from '@app/logger';
import { CommonModule } from '@app/common';
import { SecretsModule } from '@app/secrets';

@Module({
  providers: [ChildService],
  exports: [ChildService],
  imports: [
    LoggerModule,
    CommonModule,
    SecretsModule,
  ],
})
export class AuditModule {}

我的ParentModule如下:

import { ChildModule } from '@app/child';

@Module({
  imports: [SomeModule, LoggerModule, ChildModule],
  controllers: [ParentController],
  providers: [ParentService],
  exports: [ParentService],
})
export class ParentModule {}

我什至还没有通过 DI 使用这个ChildSevice

我得到的错误:

Error: Nest can't resolve dependencies of the ChildService (LoggerService, CommonService, ?). Please make sure that the argument SecretsService at index [2] is available in the AuditModule context.

Potential solutions:
- If SecretsService is a provider, is it part of the current AuditModule?
- If SecretsService is exported from a separate @Module, is that module imported within AuditModule?
  @Module({
    imports: [ /* the Module containing SecretsService */ ]
  })

据我所知,如果我可以将一个模块(在我的例子中是 ChildModule)导入父模块,那么所有 ChildModule 依赖项都将得到解决。我的意思是我不需要手动在父模块的提供者中提及 ChildModule 的所有依赖项。

无法得到任何线索这里缺少什么。

【问题讨论】:

    标签: typescript ts-jest


    【解决方案1】:

    ChildService构造函数中的第三个参数是SecretsServiceSecretsService 可能在 SecretsModule 中。因此,要在 AuditModule 上下文中使用 SecretsService,您需要将该服务作为出口商SecretsModule中,然后您可以通过导入相关模块在您想要的每个模块中使用此服务。

    所以变化是:

    //secrets.module.ts
    @Module({
      imports: [...],
      controllers: [...],
      providers: [...],
      exports: [SecretsService],
    })
    export class SecretsModule {}
    

    如果您有任何其他类似情况,请执行相同的操作。

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 2021-10-17
      • 2022-11-12
      • 2023-04-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      相关资源
      最近更新 更多