javascript - 如何在 NEST Js 的 Global-interceptor 中使用 Service
问题描述
我想在全局拦截器中使用服务。
我的代码如下所示:
import { VariablesService } from '../app/modules/variables/variables.service';
@Interceptor()
export class globalInterceptor implements NestInterceptor {
constructor(private service: VariablesService) {
console.log('contructor running', service); //getting null here
}
在server.ts上,我首先是这样初始化的:
app.useGlobalInterceptors(new globalInterceptor())
但是在注入服务之后我必须做一些修改,因为现在需要参数globalInterceptor()
const variableService = await app.get<VariablesService>(VariablesService);
app.useGlobalInterceptors(new globalInterceptor(variableService));
现在我遇到的问题是service
,null
我无法创建服务对象。
解决方案
您可以直接从模块定义中注册一个全局拦截器:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: GlobalInterceptor,
},
],
})
export class ApplicationModule {}
这在官方文档中列出,here。
推荐阅读
- django - Django:通过字段关系注释用户的回复计数,以及查询优化
- .net - 异常后在调试器中继续代码
- c# - Ubuntu 上 C# 的 VSCode 自动补全
- ruby-on-rails - 在 ubuntu 20.04 上运行 rake db:create 时出现错误“LoadError:无法加载此类文件 -- 赛璐珞/当前”
- c# - 如何使用 WMI c# Windows 窗体刷新设备列表
- antlr - TestRig / grun 在解析示例文件时卡住了
- apache-camel - 消息在执行完成后写入队列并且生产者已停止
- node.js - 为什么我非常基本的 node.js 端点超时?
- ocaml - 有必要使用 Obj.magic 吗?
- r - 如何使用R在带有多个小表的Excel工作表中添加带有标题数据的列?