首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript装饰器:从方法装饰器中获取类装饰器的值

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

Stack Overflow用户
提问于 2019-08-29 17:45:25
回答 1查看 222关注 0票数 1

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

代码语言:javascript
复制
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。

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

EN

回答 1

Stack Overflow用户

发布于 2021-04-15 18:45:11

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

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57707455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档