【问题标题】:Nest can't resolve dependencies of the AuthenticationServiceNest 无法解析 AuthenticationService 的依赖关系
【发布时间】:2022-01-29 22:23:24
【问题描述】:

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

当我运行代码时,会出现这样的错误。

**

[Nest] 16236 - 01/29/2022, 7:16:06 PM 错误 [ExceptionHandler] Nest 无法解析 AuthenticationService (?, JwtService,配置服务)。请确保参数 索引 [0] 处的 UsersService 在 AuthenticationModule 中可用 语境。潜在的解决方案:

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

**

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

这是我的用户模块:

@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>,
  ) {}

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

【问题讨论】:

    标签: javascript angular nestjs


    【解决方案1】:

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

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

    exports数组说明:

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

    更多模块详情:https://docs.nestjs.com/modules

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 2018-11-21
    • 2020-03-12
    • 2020-07-03
    • 2021-04-28
    • 2020-03-07
    • 2019-12-15
    • 2020-12-14
    相关资源
    最近更新 更多