我在后端中使用Nest JS
。我有日志记录服务scoped.Request
@Injectable({ scope: Scope.REQUEST })
export class LoggingService extends BaseLoggerService implements LoggerService {
constructor(readonly configService: ConfigurationService, @Inject(RequestContextService) readonly requestContextService: IRequestContextService) {}
我有需要记录服务的全局拦截器。
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(@Inject(LoggingService) private readonly logger: LoggingService) {
} }
现在在app.ts中,我试图绕过useGlobalInterceptors
的实例来定义Logging service
。但是,它在npm run start
上引发错误。
app.useGlobalInterceptors(new LoggingInterceptor(app.get(LoggingService)));
错误
2020-02-20T10:51:54.409Z ERROR [object Object] (RID:NOT_SET RP:NOT_SET TK:) (AN:NOT_SET COM:NOT_SET UAN:NOT_SET) LoggingService is marked as a scoped provider. Request and transient-scoped providers can't be used in combination with "get()" method. Please, use "resolve()" instead. Error: LoggingService is marked as a scoped provider. Request and transient-scoped providers can't be used in combination with "get()" method. Please, use "resolve()" instead.
答案 0 :(得分:0)
由于错误状态,LoggerService
的作用域为REQUEST
,因此您需要使用await app.resolve<LoggingService>(LoggingService)
,但是,您可能想做的是在全局范围内绑定拦截器,然后让Nest通过将拦截器添加到providers
数组中来处理依赖项注入:
@Module({
imports: [...],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor
},
...
]
})
export class AppModule {}
要记住的一点是,拦截器已经具有可用的整个请求上下文。另外,我不确定增强器在成为REQUEST范围的情况下如何工作(如果它具有REQUEST范围的依赖项,将会发生这种情况),因此请记住,这可能不是最佳的前进途径。