我使用的是reflect-metadata 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()的注释说,
获取目标上提供的元数据键的元数据值对象或它的原型链。
然而我什么也没得到。如果我像下面这样给MyCustom类添加@Component,
@Component({
selector: 'hello'
})
export class MyCustom {}
我得到一个结果,那是对"MyCustom"的注释。
为什么我没有得到子类上的注释?
元数据是为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;
注册表和组件不必在同一个文件中,只要在需要的地方导入即可。
然后从你的主组件中很容易得到所有这些组件