小编hik*_*neh的帖子

NestJs - 从自定义装饰器内的服务调用方法

基于这个答案,我尝试在装饰器内实现另一个服务的功能。

这是我的尝试:

export function ClearCache() {
  const injectCacheService = Inject(CacheService);

  return (target: any, _: string, propertyDescriptor: PropertyDescriptor) => {
    injectCacheService(target, 'service'); // this is the same as using constructor(private readonly logger: LoggerService) in a class

    //get original method
    const originalMethod = propertyDescriptor.value;

    //redefine descriptor value within own function block
    propertyDescriptor.value = async function (...args: any[]) {
      try {
        console.log(this);
        const service: CacheService = this.service;
        service.clearCacheById(args[1]);

        return await originalMethod.apply(this, args);
      } catch (error) {
        console.error(error);
      }
    };
  };
} …
Run Code Online (Sandbox Code Playgroud)

decorator node.js typescript nestjs

2
推荐指数
1
解决办法
7569
查看次数

标签 统计

decorator ×1

nestjs ×1

node.js ×1

typescript ×1