Reputation: 97
How can I use forwardRef() for circular dependency? I did the same as the documentation but didn't work it gives me this error: The module at index [1] of the GroupModule "imports" array is undefined.
Potential causes:
Scope [AppModule -> EntityModule -> BranchModule] +91ms
Upvotes: 2
Views: 3271
Reputation: 97
the circular dependency happened when two modules are calling each other, for example, if I have an animal module and a cats model calling each other:
in 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 { }
in 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 { }
in animal.service.ts:
export class AnimalService {
constructor(
@Inject(forwardRef(() => CatService)) private readonly catService: CatService,
) {
}//rest of code here}
in cat.service.ts:
export class CatService {
constructor(
@Inject(forwardRef(() => AnimalService)) private readonly animalService: AnimalService,
) {
}//rest of code here}
Upvotes: 2