【问题标题】:reflect-metadata and querying the object for decorators反射元数据并查询装饰器的对象
【发布时间】:2017-05-02 08:42:45
【问题描述】:

我有一个什么都不做的装饰器:

export function myDecorator(target: any, key: string) {
   var t = Reflect.getMetadata("design:type", target, key);
}

我将这个装饰器与一个类的属性一起使用:

export class SomeClass {

    @globalVariable
    someProperty: string;

    @globalVariable
    fakeProperty: number;
}

现在,我要做的是,获取使用 @globalVariable 装饰器装饰的类的所有属性。

我尝试使用“反射元数据”:

Reflect.getMetadata('globalVariable', this);

但我得到的只是“未定义”。这是否可能与反射元数据或我完全错了?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您需要通过以下方式实现 globalVariable:

    function globalVariable(target: any, propertyKey: string | Symbol): void {
        let variables = Reflect.getOwnMetadata("globalVariable", target.constructor) || [];
        variables.push(propertyKey);
        Reflect.defineMetadata("globalVariable", variables, target.constructor);
    }

    然后,在运行时,您就可以调用

    Reflect.getMetadata('globalVariable', this);

    如你所愿。

    【讨论】:

      【解决方案2】:

      在定义类时,每个类中的属性定义都会调用一次属性装饰器。

      这意味着如果你用@myDecorator 装饰 SomeClass 中的属性:

      export class SomeClass {
          @myDecorator
          someProperty: string;
      }
      

      然后 myDecorator 函数将被调用:
      目标:(SomeClass 定义)
      键:(属性的名称)

      当您通过“emitDecoratorMetadata”属性启用元数据时,TypeScript 编译器将生成以下元数据属性:

      'design:type''design:paramtypes''design:returntype'

      然后,您可以使用上述任何键调用 Reflect.getMetadata。即:

      Reflect.getMetadata('design:type', ...)
      Reflect.getMetadata('design:paramtypes',...)
      Reflect.getMetadata('design:returntype', ...)
      

      您不能使用装饰器的名称调用 Reflect.getMetadata。

      【讨论】:

      • 感谢您的帮助。枚举一个类的所有修饰属性怎么样?
      • 我相信您需要创建自己的装饰器来存储这些信息。请记住,属性装饰器只是一个函数,每个装饰属性调用一次。如果您存储了这些信息,您以后可以检索它...
      • 你有没有做过@blorkfish 的最后一条评论?这恰好正是我所需要的。
      • @blorkfish 有这方面的文档吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 2017-10-30
      • 2013-01-14
      • 2015-08-19
      • 2015-09-03
      • 2018-07-10
      相关资源
      最近更新 更多