簡體   English   中英

Nest 無法解析 AuthenticationService 的依賴關系

[英]Nest can't resolve dependencies of the AuthenticationService

我是嵌套 js 的新手,我正在嘗試使用 JWT 令牌實現對嵌套 js 的身份驗證。 我流這篇文章來實現我的身份驗證代碼。

當我運行代碼時,我收到這樣的錯誤。

**

[Nest] 16236 - 2022 年 1 月 29 日,下午 7:16:06 錯誤 [ExceptionHandler] Nest 無法解析 AuthenticationService(?、JwtService、ConfigService)的依賴項。 請確保索引 [0] 處的參數 UsersService 在 AuthenticationModule 上下文中可用。 潛在的解決方案:

  • 如果 UsersService 是提供者,它是當前 AuthenticationModule 的一部分嗎?
  • 如果 UsersService 是從單獨的 @Module 導出的,那么該模塊是在 AuthenticationModule 中導入的嗎? @Module({ imports: [ /* 包含 UsersService 的模塊 */ ] })

**

而且我不知道我的代碼有什么問題。

這是我的用戶模塊:

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

這是我的身份驗證模塊:

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

這是我的應用模塊:

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

我的身份驗證服務文件:

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

出口數組說明:

此模塊提供的提供程序子集,應該在導入此模塊的其他模塊中可用。 您可以使用提供者本身或僅使用其令牌(提供值)

有關模塊的更多詳細信息: https://docs.nestjs.com/modules

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM