Nestjs中的Interceptor内部实例化服务类



我会在Nestjs中的Interceptor中打电话(请参阅DOC(,这是我制作的方式

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

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];
  }
}

我遇到了一个错误,即配置不确定

无法读取未定义的属性

但我已经正确实例化了 ConfigService

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

在依赖项注入方面,从任何模块外部注册的全局拦截器都不能注入依赖项,因为这是在任何模块的上下文之外完成的。

因此,如果在您的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 {}

,也可以用

在控制器中绑定拦截器
@UseInterceptors(HttpInterceptor)
export class YourController {}

最新更新