【问题标题】:instantiate service Class inside Interceptor in Nestjs在 Nestjs 的 Interceptor 中实例化服务类
【发布时间】:2019-12-21 12:18:24
【问题描述】:

我会在 NestJS (see 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
  }
}

她的配置服务

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 未定义的错误

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

但我已经正确实例化了ConfigService

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

【问题讨论】:

  • 但是我已经正确地实例化了 ConfigService - 我不是很生气:似乎 ConfigService 没有注入 - 所以你应该发布相关的 Module definition 以便我们可以看到提供者
  • 你能分享一下你的代码吗
  • 我收到了回复 here 我已经在模块中导入了拦截器,而不是在 main.ts 中调用它

标签: typescript nestjs


【解决方案1】:

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

所以如果在你的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 {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2019-09-13
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多