【问题标题】:Reflect-metadata: check if property has "Output()" decorator反射元数据:检查属性是否具有“输出()”装饰器
【发布时间】:2019-12-16 14:17:36
【问题描述】:

我正在编写一个 Angular 库。一个对象包装了一个 Angular 组件实例,并且该对象必须订阅组件实例中所有标有 Output 装饰器的主题。 这是我迄今为止在构造函数中编写的代码:

const componentProperties = Object.keys(this.component.instance);
componentProperties.forEach(property => {
    if (!!Reflect.getMetadata('Output', this.component.instance, property)) {
        //do stuff to subscribe
    }
});

Reflect.getMetadata 正在返回 false 还分析角度组件内的属性“testEvent”:

export class Test2Component implements OnInit {
  public text: string;
  @Output() testEvent = new EventEmitter();
  //...
}

我做错了什么?

更新

目前,我使用了这个技巧:

 componentProperties.forEach(property => {
      if (
        this.component.instance.constructor.__prop__metadata__ &&
        this.component.instance.constructor.__prop__metadata__[property]
      ) {
        this.component.instance.constructor.__prop__metadata__[property].forEach(decorator => {
          if (Reflect.getPrototypeOf(decorator)['ngMetadataName'] === 'Output') {
            let eventName = decorator.bindingPropertyName ? decorator.bindingPropertyName : property;
            this.registerEvent(property);
            this.emitters.push(eventName);
          }
        });
      }
    });

很丑,但是可​​以用

【问题讨论】:

    标签: angular reflect-metadata


    【解决方案1】:

    我通过ComponentFactoryResolver找到了更好的方法来做同样的事情:

    const factory = componentFactoryResolver.resolveComponentFactory(this.component.componentType);
    const eventEmitters = factory.outputs;
    eventEmitters.forEach(e => {
      this.registerEvent(e.propName, e.templateName);
      this.emitters.push(e.templateName);
    });
    

    【讨论】:

      猜你喜欢
      • 2011-07-26
      • 1970-01-01
      • 2016-12-22
      • 2020-07-09
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      相关资源
      最近更新 更多