Nest 无法解析 AuthenticationService 的依赖关系

Zen*_*ixo 3 javascript angular nestjs

我是 Nest js 的新手,我正在尝试使用 JWT 令牌对 Nest js 进行身份验证。我通过这篇文章来实现我的身份验证代码。

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

**

[Nest] 16236 - 01/29/2022, 7:16:06 PM 错误 [ExceptionHandler] Nest 无法解析 AuthenticationService(?、JwtService、ConfigService)的依赖项。请确保索引 [0] 处的参数 UsersService 在 AuthenticationModule 上下文中可用。潜在的解决方案:

  • 如果 UsersService 是提供者,它是当前 AuthenticationModule 的一部分吗?
  • 如果 UsersService 是从单独的 @Module 导出的,那么该模块是否在 AuthenticationModule 中导入?@Module({ import: [ /* 包含 UsersService 的模块 */ ] })

**

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

这是我的用户模块:

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

这是我的身份验证模块:

@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 {}
Run Code Online (Sandbox Code Playgroud)

这是我的应用程序模块:

@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 {}
Run Code Online (Sandbox Code Playgroud)

我的身份验证服务文件:

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

我的用户服务文件:

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

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

小智 5

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

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

导出数组说明:

此模块提供的提供程序子集,并且应该在导入此模块的其他模块中可用。您可以使用提供者本身或仅使用其令牌(提供值)

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