Nest 无法解析 AuthenticationService 的依赖关系

Nest can't resolve dependencies of the AuthenticationService

我是 nest js 的新手,我正在尝试使用 JWT 令牌对 nest js 进行身份验证。我流 This 文章来实现我的验证码。

当我 运行 代码时,我得到这样的错误。

**

[Nest] 16236 - 01/29/2022, 7:16:06 PM ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthenticationService (?, JwtService, ConfigService). Please make sure that the argument UsersService at index [0] is available in the AuthenticationModule context. Potential solutions:

  • If UsersService is a provider, is it part of the current AuthenticationModule?
  • If UsersService is exported from a separate @Module, is that module imported within AuthenticationModule? @Module({ imports: [ /* the Module containing UsersService */ ] })

**

而且我不知道我的代码有什么问题。

这是我的用户模块:

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}

这是我的 AuthenticationModule:

@Module({
  imports: [
    UsersModule,
    PassportModule,
    ConfigModule,
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get('JWT_SECRET'),
        signOptions: {
          expiresIn: `${configService.get('JWT_EXPIRATION_TIME')}s`,
        },
      }),
    }),
  ],
  controllers: [AuthenticationController],
  providers: [AuthenticationService, LocalStrategy, JwtStrategy],
})
export class AuthenticationModule {}

这是我的 AppModule:

@Module({
  imports: [
    TypeOrmModule.forRoot(ORM_CONFIG),
    ConfigModule.forRoot({
      validationSchema: Joi.object({
        JWT_SECRET: 'ABC',
        JWT_EXPIRATION_TIME: '1d',
      }),
    }),
    ItemModule,
    CategoryModule,
    ItemHasCategoryModule,
    OrderModule,
    OrderHasItemModule,
    PaymentModule,
    CustomerModule,
    UsersModule,
    AuthenticationModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

我的 AuthenticationService 文件:

@Injectable()
export class AuthenticationService {
  constructor(
    private readonly usersService: UsersService,
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
  ) {}

我的用户服务文件:

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
  ) {}

如果有人知道这个问题的答案......我真的需要你的帮助......我为这个错误苦苦挣扎了几个小时......谢谢。

您需要导出 UserService 才能在其他模块中使用它。

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService] 
}) 
export class UsersModule {}

导出数组说明:

the subset of providers that are provided by this module and should be available in other modules which import this module. You can use either the provider itself or just its token (provide value)

有关模块的更多详细信息:https://docs.nestjs.com/modules