Nest can't resolve dependencies of the service

2020-04-29 00:32发布

问题:

I am trying to use @nestjs/jwt. Particularly its registerAsync method (my config service loads the configuration asynchronously). I am registering JwtModule in the AuthModule, which then loads specific modules for each login/registration providers. Then I add JwtService to the providers of EmailService but it fails.

The structure of the application is as follows (very schematic):

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

Application fails with this error upon startup:

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)

What did I miss?

回答1:

Services are not global but can only be used in the modules that provide them themselves or import them from another module that exports the service.

The problem here is that the EmailService depends on the JwtService but the EmailAuthModule does neither provide the JwtService itself nor import a module that exports the JwtService. (Unfortunately, you left out the EmailAuthModule's imports here.)

So to solve this you have to import either the JwtModule itself or another module that exports the JwtModule in the EmailAuthModule.