【问题标题】:How can i set when to run Typescript decorators我如何设置何时运行 Typescript 装饰器
【发布时间】:2022-01-30 07:16:12
【问题描述】:

当我为方法定义参数化装饰器时,装饰器在方法运行之前开始运行。

我希望装饰器在方法被调用后运行。

 function fooDecorator(value: boolean) {
  console.log('fooDecorator init');
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  };
}

class Foo{


  @fooDecorator(true)
  foo(){

  }

}

app.listen(5000, () => console.log("server started"));




// Output 
fooDecoratorinit
server started

【问题讨论】:

标签: javascript typescript decorator aop interceptor


【解决方案1】:

TypeScript 方法装饰器在类初始化期间运行,因此它们可以装饰方法;见documentation。如果您希望装饰器在方法被调用时执行某些操作,您可以让装饰器将方法包装在另一个函数中,该函数执行您希望它执行的操作:

function fooDecorator(flag: boolean) {
    return function (target: any, propertyKey: string; descriptor: PropertyDescriptor) {
        const original = target[propertyKey];
        return {
            ...descriptor,
            value(...args: any[]) {
                console.log("Inserted behavior, flag = " + flag);
                return original.apply(this, args);
            }
        }
    };
}

class Foo{
    @fooDecorator(true)
    foo(){
        console.log("Original foo");
    }
}

const f = new Foo();
f.foo();

Playground link

输出:

插入行为,标志 = true 原始富

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-18
    • 2018-06-08
    • 2019-08-22
    • 2017-11-27
    • 2022-08-15
    • 2023-04-09
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多