angular - 如何将请求范围服务的实例传递给全局拦截器
问题描述
我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.
解决方案
正如错误所述,由于LoggerService
是REQUEST
作用域,您需要使用await app.resolve<LoggingService>(LoggingService)
,但是,您可能想要做的是全局绑定拦截器,并让 Nest 通过将拦截器添加到providers
数组来处理依赖注入,如下所示:
@Module({
imports: [...],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor
},
...
]
})
export class AppModule {}
需要记住的是,拦截器已经拥有可用的整个请求上下文。另外,我不确定增强器在 REQUEST 范围内如何发挥作用(如果它具有 REQUEST 范围的依赖项会发生这种情况),因此请记住,这可能不是最好的前进路线。
推荐阅读
- memory - 为什么编译后会分配两块内存区域,是不是很浪费内存?
- html - 页脚没有响应应有的响应
- azure - 如何将 Orchard Core 从 localhost 部署到 Azure
- css - 边框在出现时正在移动 div
- webhooks - 使用 Webhook 触发器从 Zap 响应源
- python - python - 从原始 ext4 图像读取文件信息和权限
- reactjs - 如何使用 Azure AD 获取用户配置文件详细信息
- webpack - 网页包。构建组件库
- node.js - node.js node-red - 将 Base64 字符串转换为 uint8array
- java - 在两个元素之间替换数字 Java 中的 .(dot)