0

我正在使用反射元数据 0.1.2。我有一个父类作为“MyCustom”。

export class MyCustom {}

我的“Home”组件类扩展了这个“MyCustom”类。

@Component({
  selector: 'home',
  templateUrl: './app/components/home/home.html',
  styleUrls: ['./app/components/home/home.css']
})
export class Home extends MyCustom {
}

我的意图是使用以下方法调用获取扩展“MyCustom”类的所有类的元数据。

let annotations = Reflect.getMetadata('annotations', MyCustom);

对 Reflect.getMetadata() 方法的评论说,

获取目标对象或其原​​型链上提供的元数据键的元数据值。

然而我什么也得不到。如果我将@Component 添加到“MyCustom”类,如下所示,

@Component({
  selector: 'hello'
})
export class MyCustom {}

我得到一个结果,即“MyCustom”上的注释。

为什么我没有得到子类的注释?非常感谢任何帮助。

4

1 回答 1

1

元数据是为Home而不是为保存的MyCustom,继承在这里不起作用。

您可能会做的是拥有自己的装饰器,它将为父类添加元数据,然后Component使用所需的值调用装饰器。
就像是:

function MyComponent(props: any) {
    return (ctor) => {
        Reflect.defineMetadata('annotations', ctor.prototype.name, ctor.prototype);
        return Component(props)(ctor);
    }
}

@MyComponent({
    selector: 'home',
    templateUrl: './app/components/home/home.html',
    styleUrls: ['./app/components/home/home.css']
})
class Home extends MyCustom {}

我没有测试过它,也没有做过类似的事情,但它应该可以工作。


为什么不使用“注册表”?
有这样的事情:

const REGISTRY: { [name: string]: MyCustom } = {};

然后,为每个这样的组件注册它:

class Home extends MyCustom {
    ...
}

REGISTRY["home"] = Home;

注册表和组件不必在同一个文件中,只要在需要的地方导入即可。

然后从您的主要组件中很容易拥有所有这些组件。

于 2016-10-10T11:22:15.047 回答