首页 > 解决方案 > 如何将请求范围服务的实例传递给全局拦截器

问题描述

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.

标签: angularinterceptornestjs

解决方案


正如错误所述,由于LoggerServiceREQUEST作用域,您需要使用await app.resolve<LoggingService>(LoggingService),但是,您可能想要做的是全局绑定拦截器,并让 Nest 通过将拦截器添加到providers数组来处理依赖注入,如下所示:

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

需要记住的是,拦截器已经拥有可用的整个请求上下文。另外,我不确定增强器在 REQUEST 范围内如何发挥作用(如果它具有 REQUEST 范围的依赖项会发生这种情况),因此请记住,这可能不是最好的前进路线。


推荐阅读