首页 > 解决方案 > 在 typescript 中读取类装饰器信息

问题描述

我有一个用属性装饰的类。

我想阅读构造函数(或其他方法)中的属性。

我已经尝试在该类上使用 Reflect 和所有可能的方法,但我只得到未定义

这个类看起来像这样

@inject(Element)
@bindable('color')
export class Messagebarhost {

public element: HTMLElement;

  constructor(element) {
  console.log(Reflect.getMetadata("design:paramtypes", this));
  // prints undefined
  // somehow I want to read the value 'color'
  }
}

如果我在创建装饰器的捆绑 js 文件中设置断点。如果我在调试器中输入正确的值,下面的行将打印正确的值

r.__metadata__.undefined["aurelia:resource"].properties[0]

标签: typescriptaurelia

解决方案


我认为你不应该把装饰器放在类上,而应该放在一个字段上,如下所示:

@inject(Element)
export class Messagebarhost {

  public element: HTMLElement;
  @bindable color;


  constructor(element) {
     // this.color is not bound here yet.
  }

  attached () {
    // You need to wait till the attached or the bind function is
    // called to get the correct value in this.color.
  }
}

推荐阅读