【问题标题】:Problem when try to inject a service into another service using nestjs尝试使用nestjs将服务注入另一个服务时出现问题
【发布时间】:2019-12-05 07:52:24
【问题描述】:

我遇到了一个问题。 我有这个示例存储库:https://github.com/pillowslept/nest-example

我想将RaceService注入HeroService,因为我想使用getById等一些方法。

我遵循此处描述的文档:https://docs.nestjs.com/modules

问题发生在我下一步的时候:

RaceModule 我添加了RaceService 作为导出:

@Module({
  imports: [TypeOrmModule.forFeature([RaceEntity])],
  controllers: [RaceController],
  providers: [RaceService],
  exports: [RaceService],
})

HeroModule我导入了RaceModule

@Module({
  imports: [RaceModule, TypeOrmModule.forFeature([HeroEntity])],
  controllers: [HeroController],
  providers: [HeroService],
})

HeroService 我为RaceService 添加了注入:

constructor(
    @InjectRepository(HeroEntity)
    private heroRepository: Repository<HeroEntity>,
    private readonly raceService: RaceService,
  ) {
  }

控制台出现错误:

Error: Nest cannot create the module instance. Often, this is because of a circular dependency between modules. Use forwardRef() to avoid it

我尝试了不同的方法来导入服务,包括创建一个新的 CommonsModule,也将 forwardRef 放入 raceService 定义中,但出现另一个错误:

Nest can't resolve dependencies of the HeroService (HeroEntityRepository, ?). Please make sure that the argument at index [1] is available in the HeroModule context.

感谢您的帮助!

【问题讨论】:

  • 我在您的 GitHub 存储库上提出了拉取请求,希望对您有所帮助。
  • @Juan 欢迎来到 SO!由于您的问题似乎已解决,请考虑将其添加为您自己问题的答案。其他人可能会从您的解决方案中受益,也可以看到您的问题已经解决。 :-)

标签: javascript node.js nestjs


【解决方案1】:

在一些帮助下,我意识到我的问题出现了,因为我在模块文件夹中创建了一个文件 index.ts(同时导出模块名称的想法),如下所示:

export { RaceModule } from './race.module';
... others

那么,当我尝试在HeroModule 导入RaceModule 时,就像这样:

import { RaceModule } from 'modules';

我的问题出现了。

我不知道为什么,而是直接从index.ts 文件引用模块导入,而不是:

import { RaceModule } from 'modules/race.module';

是我的代码的问题。

因此,根据一些建议,我创建了一些文件夹并移动了一些文件,我的项目开始正常工作。

感谢您的帮助,希望有人觉得这对您有帮助。

【讨论】:

    【解决方案2】:

    你需要在英雄模块中导入比赛模块的模块

    【讨论】:

      猜你喜欢
      • 2020-03-14
      • 2019-01-20
      • 2013-12-22
      • 2020-09-09
      • 2021-05-15
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多