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

时间:2018-09-20 07:35:56

标签: javascript node.js typescript nestjs

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

我想念什么?

1 个答案:

答案 0 :(得分:2)

服务不是全局的,只能在提供服务的模块中使用,也可以从导出服务的另一个模块中导入。

这里的问题是EmailService依赖于JwtService,但是EmailAuthModule既不提供JwtService本身,也不导入导出{{1}的模块}。 (很遗憾,您在此处省略了JwtService的{​​{1}}。)

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