简体   繁体   中英

Nest can't resolve dependencies of the

I'am trying to use AuthService into UsersService and UsersService into AuthService, so this is called "circular dependency". The issue is that "Nest can't resolve dependencies of the AuthService (UserModel, JwtService, ?). Please make sure that the argument dependency at index [2] is available in the AuthModule context."

UsersModule:

@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: User.name, schema: UserSchema
      }
    ]),
    forwardRef(() => AuthModule),
  ],
  controllers: [UsersController],
  providers: [UsersService], 
  exports: [UsersService]
}) 
export class UsersModule {}enter code here

AuthModule:

@Module({
  imports: [
    MongooseModule.forFeature([{name: User.name, schema: UserSchema}]),
    JwtModule.register({ secret: process.env.JWT_SECRET }),
    forwardRef(() => UsersModule),
  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService, JwtModule]
})
export class AuthModule {}

UsersService (works fine):

@Injectable()
export class UsersService {
  constructor(
      @InjectModel(User.name) private userModel: Model<UserDocument>,
      private jwtService: JwtService,
      private authService: AuthService
    ) {}
...

AuthService (where error occurs):

@Injectable()
export class AuthService {
  constructor(
      @InjectModel(User.name) private userModel: Model<UserDocument>, 
      private jwtService: JwtService,
      private userService: UsersService,
    ) {}
...

You've resolved the circular dependency between the modules, but not between the services. Each side of the service needs @Inject(forwardRef(() => InjectedClass)) . So your AuthService would use @Inject(forwardRef(() => UserService))

Circular dependencies are bad and trying to get around them using things like forwardRef mentioned in the other answer is not good practice.

Look into other patterns for inter-service communication. Events for example: https://docs.nestjs.com/techniques/events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM