gpt4 book ai didi

angular - 如何将 REQUEST 范围服务的实例传递给全局拦截器

转载 作者:行者123 更新时间:2023-12-05 06:20:43 24 4
gpt4 key购买 nike

我在后端使用 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.

最佳答案

作为错误状态,作为 LoggerServiceREQUEST作用域,你需要使用 await app.resolve<LoggingService>(LoggingService) ,但是,您可能想要做的是全局绑定(bind)拦截器,并让 Nest 通过将拦截器添加到 providers 来处理依赖项注入(inject)。像这样的数组:

@Module({
imports: [...],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor
},
...
]
})
export class AppModule {}

需要记住的是,拦截器已经拥有了整个请求上下文。此外,我不确定如果增强器变成 REQUEST 范围(如果它具有 REQUEST 范围的依赖项将会发生什么),它们将如何工作,所以请记住,这可能不是最好的前进路线。

关于angular - 如何将 REQUEST 范围服务的实例传递给全局拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60318279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com