【问题标题】:Nest can't resolve dependencies of the service which imports JwtServiceNest 无法解析导入 JwtService 的服务的依赖关系
【发布时间】:2019-02-24 11:01:06
【问题描述】:

我正在尝试使用@nestjs/jwt。特别是它的registerAsync 方法(我的配置服务异步加载配置)。我在AuthModule 中注册JwtModule,然后为每个登录/注册提供程序加载特定模块。然后我将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)

我错过了什么?

【问题讨论】:

标签: javascript node.js typescript nestjs


【解决方案1】:

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

这里的问题是EmailService 依赖于JwtService,但EmailAuthModule 本身既不提供JwtService,也不导入导出JwtService 的模块。 (很遗憾,您在这里遗漏了EmailAuthModuleimports。)

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

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多