Search code examples
javascripttypescriptsqlitenestjstypeorm

Nest can't resolve dependencies of the AuthService (?). UsersService at index [0] is available in the AuthModule context


I got this error. I try to solve this problem almost 2 days. I did not find solutions. Can anyone help me figure out this problem. To solve this problem, I used Circular dependency forward referencing in to module. But it did not work.

Error: Nest can't resolve dependencies of the AuthService (?). Please make sure that the argument UsersService at index [0] is available in the AuthModule context.

Potential solutions:
- Is AuthModule a valid NestJS module?
- If UsersService is a provider, is it part of the current AuthModule?
- If UsersService is exported from a separate @Module, is that module imported within AuthModule?
  @Module({
    imports: [ /* the Module containing UsersService */ ]
  })

    at Injector.lookupComponentInParentModules (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:244:19)   
    at Injector.resolveComponentInstance (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:197:33)
    at resolveParam (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:117:38)
    at async Promise.all (index 0)
    at Injector.resolveConstructorParams (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:132:27)
    at Injector.loadInstance (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:58:13)
    at Injector.loadProvider (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\injector.js:85:9)
    at C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\instance-loader.js:49:13
    at async Promise.all (index 3)
    at InstanceLoader.createInstancesOfProviders (C:\Users\OSMAN MERT\Desktop\candy\node_modules\@nestjs\core\injector\instance-loader.js:48:9)

users.service.ts

@Injectable()
export class UsersService {
  constructor(

  @InjectRepository(UserEntity) private repo: Repository<UserEntity>) {}
  
  async create(createUserDto: CreateUserDto):Promise<UserEntity> {
    const user = new UserEntity();
    user.firstname = createUserDto.firstname;
    user.lastname = createUserDto.lastname;
    user.email = createUserDto.email;
    
    return await this.repo.save(user) 

  }

  async findAll():Promise<UserEntity[]> {
    return await this.repo.find();
  }

  async findOne(id: number):Promise<UserEntity> {
    return await this.repo.findOne({
      select:['id','firstname','lastname',"email"],
      where:{id}
    });
  }

users.module.ts

@Module({
  imports:[TypeOrmModule.forFeature([UserEntity]),PassportModule,forwardRef(() =>AuthModule)],
  controllers: [UsersController],
  providers: [UsersService],
  exports:[UsersService]
})
export class UsersModule {}

users.entity.ts

@Entity()
export class UserEntity {
    @PrimaryGeneratedColumn()
    id: number;
   
    @Column()
    firstname: string;

    @Column()
    lastname: string;

    @Column()
    email:string;
    
   
}

auth.service.ts

@Injectable()
export class AuthService {
    constructor(@Inject('UsersService') private  userService:UsersService){}

    async validateUser(id:number,password:string){
        const user = await this.userService.findOne(id)
        if(user.id === id){
            return user
        }
        return null
    }
}

auth.module.ts

@Module({
  imports:[forwardRef(() => UsersModule)],
  providers: [AuthService,UsersService],
  exports:[AuthService]
})
export class AuthModule {}

This is my folder structure: enter image description here


Solution

  • when you import a module, you're importing the providers that it exports. I don't see any reason to have that UsersService at AuthModule as you have UsersModule imported into it.

    If you're using nestjs v8 or greater, using the string as a token for class-based providers won't work. So remove the @Inject('UsersService') from there. This seems to be the cause of your issue. Use
    @Inject(forwardRef(() => UserService)) instead

    Also, folder structure doesn't matter. Just make sure you don't have a bunch of barrel files that might introduce circular imports. You can learn more on this here: Circular Dependencies in NestJS and how to Avoid Them