【发布时间】: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