在Nestjs中实例化拦截器内的服务类

inf*_*dev 6 typescript nestjs

我会在 NestJS 中调用拦截器内的服务(请参阅文档),这就是我的制作方法

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
  }
}
Run Code Online (Sandbox Code Playgroud)

她的 ConfigService

export class ConfigService {
  private readonly envConfig: { [key: string]: string };

  constructor(filePath: string) {    
    this.envConfig = dotenv.parse(fs.readFileSync(path.join(__dirname, filePath)));
  }

  get(key: string): string {
    return this.envConfig[key];
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,指出 configService 未定义

无法读取未定义的属性“get”

但我已经ConfigService正确实例化了

我不知道为什么我不能ConfigService在拦截器内部使用

Gab*_*ile 9

就依赖项注入而言,从任何模块外部注册的全局拦截器无法注入依赖项,因为这是在任何模块的上下文之外完成的。

所以如果main.ts你正在使用

app.useGlobalInterceptors(new HttpInterceptor()); 你需要将其更改为 app.useGlobalInterceptors(new HttpInterceptor(new ConfigService()));

或者您可以将拦截器绑定到特定模块中

import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
  providers: [
    ConfigService,
    {
      provide: APP_INTERCEPTOR,
      useClass: HttpInterceptor,
    },
  ],
})
export class YourModule {}
Run Code Online (Sandbox Code Playgroud)

或者您可以将拦截器绑定在控制器中

@UseInterceptors(HttpInterceptor)
export class YourController {}
Run Code Online (Sandbox Code Playgroud)