The module at index [1] is of type "undefined". Check your import statements and the type of the module

Viewed 1870

I heve a problem with circular dependency in NestJs. Error:

Scope [AppModule -> PlanModule -> TaskModule] +17ms
Error: Nest cannot create the UserModule instance.
The module at index [1] of the UserModule "imports" array is undefined.

What I tried:

  • Use forwardRef in resolver file in both user and task files in construcor:
@Inject(forwardRef(() => TaskService))
private readonly tasksService: TaskService
  • Implements OnModuleInit interface:
onModuleInit() {
  this.userService = this.moduleRef.get(UserService);
}
  • Use imports without index.ts file:
import { TaskModule } from '../task/task.module';

user.module

@Module({
  providers: [UserService, UserResolver],
  exports: [UserService],
  imports: [JournalModule, PlanModule, TaskModule],
})
export class UserModule {}

task.module

@Module({
  providers: [TaskService, TaskResolver],
  exports: [TaskService],
  imports: [UserModule],
})
export class TaskModule {}

plan.module

@Module({
  providers: [PlanService, PlanResolver, GoalResolver],
  imports: [TaskModule, ProgramModule],
  exports: [PlanService],
})
export class PlanModule {}
1 Answers

Your UserModule import the TaskModule and the TaskModule imports the UserModule, so you need to set up forward references for these module imports along with the service injections. It would look like this:

user.module.ts

@Module({
  providers: [UserService, UserResolver],
  exports: [UserService],
  imports: [JournalModule, PlanModule, forwardref(() => TaskModule)],
})
export class UserModule {}

task.module.ts

@Module({
  providers: [TaskService, TaskResolver],
  exports: [TaskService],
  imports: [forwardRef(() => UserModule)],
})
export class TaskModule {}
Related