Typescript装饰器:从方法装饰器获取类装饰器值

时间:2019-08-29 09:45:24

标签: typescript typescript-decorator reflect-metadata

我有一个类装饰器(fooAnnotation)和方法装饰器(barDecorator)。

[[key1, value1], [key2, value2], [key3, value3]]

我的需要是barAnnotation必须使用fooAnnotation的值,但是不幸的是,打字稿在方法装饰器之后评估类装饰器,因此在barAnnotation内部尚未定义fooAnnotationMetadata。

方法装饰器如何检索类装饰器的值?

1 个答案:

答案 0 :(得分:0)

因为 Class Decorator 已经在类声明的末尾执行了。所以,改变主意,你应该在属性装饰器中存储一些东西,并在类装饰器中处理所有内容。

const innerTempPropsName = '__TempProperties__';

function fooAnnotation(value: string){
  console.log('fooAnnotation init...');
  return (ctor: any): void => {
    console.log('fooAnnotation called...');
    Reflect.defineMetadata('fooAnnotation', value, target);
    const vProps = ctor[innerTempPropsName];
    // now process the vProps...
    delete ctor[innerTempPropsName];
  };
};

function barAnnotation(value: string){
  console.log('barAnnotation init...');
  return (ctorPrototype: any, propertyKey: any): void => {
    console.log('barAnnotation called...');
    const ctor = ctorPrototype.constructor;
    let vProps = ctor[innerTempPropsName];
    if (!vProps) ctor[innerTempPropsName] = vProps = {};
    // store temp properties into vProps
    // vProps[propertyKey] = {value, }
    Reflect.defineMetadata('barAnnotation', value, target);
    ...
  };
};



@fooAnnotation('fooAnnotationValue')
class Foo{

 @barAnnotation('barAnnotationValue')
 public bar: string;
}