[英]How to use Service in Global-interceptor in NEST Js
我想在全局拦截器中使用服务。
我的代码如下所示:
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 。
之后,您必须在当前拦截器模块中导入 VariablesService 模块以进行二元注入
constructor(@Inject(VariablesService) private service: VariablesService) { console.log('contructor running', service); // }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.