由于全局注册的Guard需要Reflector,JwtService和ConfigService,因此决定制作一个全局模块,将上述依赖项导入自身。
@Global()
@Module({
imports: [
ConfigModule.forRoot({
...
}),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory(configService: ConfigService): JwtModuleOptions {
return {
signOptions: {
algorithm: 'HS256',
issuer: configService.get('JWT_ISSUER'),
},
};
},
}),
Reflector,
],
})
export class CommonModule {}
然后将其导入 AppModule:
@Module({
imports: [
CommonModule /* <-- */ ,
...
],
controllers: [],
providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
})
export class AppModule {}
此外Guard,我使用JwtServicein JwtFactoryService,用于生成用于身份验证的令牌。由于它JwtModule已经在全球范围内注册,我没有将它导入到 AuthModule 中,但由于某种原因,来自的依赖项CommonModule不会迁移到AuthModule.
Potential solutions:
- If JwtService is a provider, is it part of the current AuthModule?
- If JwtService is exported from a separate @Module, is that module imported within AuthModule?
@Module({
imports: [ /* the Module containing JwtService */ ]
})
Error: Nest can't resolve dependencies of the JwtFactoryService (?, ConfigService). Please make sure that the argument JwtService at index [0] is available in the AuthModule context.
将导入
CommonModule模块的所有服务添加到提供程序部分,然后添加到导出。我不知道它是否是拐杖,但它有效。