我遇到了问题。 我有以下示例存储库: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.
感谢您的帮助!
答案 0 :(得分:1)
在一些帮助下,我意识到我的问题出现了,因为我在modules文件夹中创建了一个文件index.ts
(想法是立即导出模块名称),像这样:
export { RaceModule } from './race.module';
... others
因此,当我尝试在RaceModule
处导入HeroModule
时,像这样:
import { RaceModule } from 'modules';
出现我的问题。
我不知道为什么,但是直接引用模块从index.ts
文件导入,而不是:
import { RaceModule } from 'modules/race.module';
是我的代码问题。
因此,按照一些建议,我创建了一些文件夹并移动了一些文件,并且我的项目开始正常运行。
感谢帮助,希望有人能对此有所帮助。
答案 1 :(得分:0)
您需要将比赛模块导入到英雄模块中