Почему сервис не может получить зависимости глобального модуля?
Так как глобально зарегистрированный 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, я использую JwtService в 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.
Ответы (1 шт):
Автор решения: Dmitriy Grape
→ Ссылка
Добавил все сервисы импортируемых в CommonModule модулей в секцию providers, а затем и в exports. Не знаю, костыль это или нет, но оно работает.
@Global()
@Module({
imports: [
ConfigModule.forRoot({}),
JwtModule.registerAsync({})
Reflector,
],
providers: [ConfigService, JwtService, Reflector],
exports: [ConfigService, JwtService, Reflector],
})
export class CommonModule {}