1

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

import 'reflect-metadata';

function fooAnnotation(value: string){
  console.log('fooAnnotation init...');
  return (target: any): void => {
    console.log('fooAnnotation called...');
    Reflect.defineMetadata('fooAnnotation', value, target);
  };
};

function barAnnotation(value: string){
  console.log('barAnnotation init...');
  return (target: any, propertyKey: any): void => {
    console.log('barAnnotation called...');
    Reflect.defineMetadata('barAnnotation', value, target);
    ...
    const fooAnnotationValue = Reflect.getMetadata('fooAnnotation', target);

   // :( fooAnnotationValue is undefined!!!
  };
};



@fooAnnotation('fooAnnotationValue')
class Foo{

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

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

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

4

1 回答 1

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;
}
于 2021-04-15T10:45:10.790 回答