NestJS 依赖问题

NestJS dependency issue

提问人:Majva 提问时间:11/15/2023 更新时间:11/15/2023 访问量:24

问:

NestJS 无法解析我的服务的依赖项, 错误显示:Nest 无法解析 AuthService 的依赖项(?、JwtService、ConfigService、+、EventEmitter、+、MailerService、MessageService)。请确保索引 [0] 处的参数依赖项在 AuthModule 上下文中可用。

app.module.ts(应用模块.ts)

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: [`.env.stage.${process.env.STAGE}`],
      validationSchema: envValidationSchema,
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: 'postgres',
        autoLoadEntities: true,
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: true,
        host: configService.get('DB_HOST'),
        port: configService.get('DB_PORT'),
        username: configService.get('DB_USERNAME'),
        password: configService.get('DB_PASSWORD'),
        database: configService.get('DB_DATABASE'),
      }),
    }),
    AuthModule,
    MessageModule,
    EventEmitterModule.forRoot(),
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: ATGuard,
    },
    {
      provide: APP_GUARD,
      useClass: ActiveUserGuard,
    },
  ],
})
export class AppModule {}

auth.module.ts(auth.module.ts)

@Module({
  imports: [
    ConfigModule,
    TypeOrmModule.forFeature([User, Device, VerificationCode]),
    JwtModule.register({}),
    forwardRef(() => MessageModule),
  ],
  controllers: [AuthController, UsersController, DevicesController],
  providers: [
    AuthService,
    UserRepository,
    UsersService,
    ATStrategy,
    RTStrategy,
    DevicesService,
    VerificationCodesService,
  ],
  exports: [UsersService, AuthService, UserRepository],
})
export class AuthModule {}

users.service.ts:

@Injectable()
export class UsersService {
  constructor(
    private repo: UserRepository,
    private readonly config: ConfigService,
  ) {}
}

auth.service.ts:

export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
    private config: ConfigService,
    private deviceService: DevicesService,
    private eventEmitter: EventEmitter2,
    private verificationCodesService: VerificationCodesService,
    private mailerService: MailerService,
    @Inject(forwardRef(() => MessageService))
    private messageService: MessageService,
  ) {}
}

如您所见,nest 无法将 UsersService 注入 AuthService,此外,DevicesService 和 VerificationCodeService 在错误消息中显示为 +。它们都在 Auth 模块中。

有什么想法吗?

JavaScript TypeScript 依赖注入 nestjs

评论

1赞 Jay McDoniel 11/16/2023
在 和 之间可能有一个循环导入路径(不一定是类之间的循环依赖关系,而是文件的循环导入链)。您能否提供对代码的访问,或在没有任何私有代码的情况下进行复制,以便我们帮助追踪导致问题的导入?AuthServiceUserService

答: 暂无答案