Typescript 在Nestjs中实例化拦截器内的服务类
我会在NestJS()中调用拦截器内的服务,下面是我如何Typescript 在Nestjs中实例化拦截器内的服务类,typescript,nestjs,Typescript,Nestjs,我会在NestJS()中调用拦截器内的服务,下面是我如何 export class HttpInterceptor implements NestInterceptor { constructor(private configService:ConfigService){} intercept(context: ExecutionContext, next: CallHandler): Observable<any> { let request = context
export class HttpInterceptor implements NestInterceptor {
constructor(private configService:ConfigService){}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
let request = context.switchToHttp().getRequest();
const apikey= this.configService.get('apikey');
const hash=this.configService.get('hash');
request.params= {apikey:apikey ,hash:hash,ts:Date.now()}
return next
}
}
我得到一个错误,configService未定义
无法读取未定义的属性“get”
但是我已经正确地实例化了ConfigService
我不知道为什么我不能在拦截器内部使用
ConfigService
就依赖项注入而言,从任何模块外部注册的全局拦截器都不能注入依赖项,因为这是在任何模块的上下文之外完成的
因此,如果在main.ts中使用
app.useGlobalInterceptors(新的HttpInterceptor())代码>
您需要将其更改为
app.useGlobalInterceptors(新的HttpInterceptor(新的ConfigService())代码>
或者,您可以将特定模块中的拦截器绑定到
import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
providers: [
ConfigService,
{
provide: APP_INTERCEPTOR,
useClass: HttpInterceptor,
},
],
})
export class YourModule {}
或者,您可以将控制器中的拦截器绑定到
@UseInterceptors(HttpInterceptor)
export class YourController {}
但是我已经正确地实例化了ConfigService-我不是那么酸:似乎ConfigService
没有被注入-所以你应该发布相关的代码,这样我们就可以看到提供者。如果你分享一点你的代码,我得到的响应是我在模块内导入了interceptor,而不是在main.ts内调用它
@UseInterceptors(HttpInterceptor)
export class YourController {}