Nest 无法解析导入 JwtService 的服务的依赖关系

Nest can't resolve dependencies of the service which imports JwtService

我正在尝试使用 @nestjs/jwt。特别是它的 registerAsync 方法(我的配置服务异步加载配置)。我在 AuthModule 中注册 JwtModule,然后为每个 login/registration 提供商加载特定模块。然后我将 JwtService 添加到 EmailService 的提供者,但它失败了。

应用的结构如下(很示意图):

app.module.ts

@Module({
  imports: [
    AuthModule,
    ...
  ]
})
export class ApplicationModule {}

auth.module.ts

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.registerAsync({
      useFactory: async (config: ConfigService) => ({
        secretOrPrivateKey: config.get('jwt.secret')
      }),
      inject: [ConfigService]
    }),
    EmailAuthModule
  ],
  exports: [JwtModule]
})
export class AuthModule {}

email.module.ts

@Module({
  imports: [...],
  controllers: [...],
  providers: [EmailService, ...]
})
export class EmailAuthModule {}

email.service.ts

@Injectable()
export class EmailService {
  constructor(
    private readonly jwtService: JwtService
  ) {}
}

应用程序在启动时失败并出现此错误:

Nest can't resolve dependencies of the EmailService (UsersService, ?). Please make sure that the argument at index [1] is available in the current context. +70ms
Error: Nest can't resolve dependencies of the EmailService (UsersService, ?). Please make sure that the argument at index [1] is available in the current context.
    at Injector.lookupComponentInExports (/Users/.../api/node_modules/@nestjs/core/injector/injector.js:146:19)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at Object.<anonymous> (/Users/.../api/node_modules/ts-node/src/_bin.ts:177:12)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)

我错过了什么?

服务不是全局的,只能在自己提供它们的模块中使用,或者从导出服务的另一个模块导入它们。

这里的问题是 EmailService 依赖于 JwtServiceEmailAuthModule 既不提供 JwtService 本身也不导入导出 [=] 的模块11=]。 (不幸的是,您在这里遗漏了 EmailAuthModuleimports。)

因此,要解决此问题,您必须导入 JwtModule 本身或导出 EmailAuthModule 中的 JwtModule 的另一个模块。