如何将forwardRef()用于循环依赖?我做了与文档相同的操作,但是没有工作,这给了我这个错误: GroupModule“导入”数组的索引[1]处的模块未定义。
潜在原因:
范围[AppModule-> EntityModule-> BranchModule] + 91ms
答案 0 :(得分:0)
循环依赖发生在两个模块相互调用时,例如,如果我有一个动物模块和一个猫模型相互调用:
在animal.module.ts中:
import { forwardRef, Module } from '@nestjs/common';
import { AnimalController } from './animal.controller';
import { AnimalService } from './animal.service';
import { AnimalRepository } from './animal.repository';
@Module({
imports: [
forwardRef(() => CatModule),
],
controllers: [AnimalController],
providers : [AnimalService, AnimalRepository],
exports : [AnimalService],
})
export class AnimalModule { }
在 cat.module.ts 中:
import { forwardRef, Module } from '@nestjs/common';
import {CatController } from './cat.controller';
import { CatService } from './cat.service';
import { CatRepository } from './cat.repository';
@Module({
imports: [
forwardRef(() => AnimalModule),
],
controllers: [CatController],
providers : [CatService, CatRepository],
exports : [CatService],
})
export class CatModule { }
在animal.service.ts:
export class AnimalService {
constructor(
@Inject(forwardRef(() => CatService)) private readonly catService: CatService,
) {
}//rest of code here}
在 cat.service.ts 中:
export class CatService {
constructor(
@Inject(forwardRef(() => AnimalService)) private readonly animalService: AnimalService,
) {
}//rest of code here}