当我的项目使用角2和角4时,我能够使用这个有用的装饰器使一个组件扩展另一个组件:
// Modified from https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7#.s9pf0649f
// by Thierry Templier.
import { Component } from '@angular/core';
export function ComponentExtender(annotation: any): ((target: Function) => void) {
return function(target: Function): void {
let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
let parentAnnotations = Reflect.getMetadata('annotations', parentTarget); // TODO: Doesn't work in Angular 5, returns undefined.
let parentAnnotation = parentAnnotations[0];
Object.keys(parentAnnotation).forEach(key => {
if (parentAnnotation[key]) {
if (!annotation[key]) {
annotation[key] = parentAnnotation[key];
}
}
});
let metadata = new Component(annotation);
Reflect.defineMetadata('annotations', [ metadata ], target);
};
}这样,您就可以创建一个扩展另一个组件类的组件类,使用@ComponentExtender而不是@ComponentExtender,并从超类继承一些东西,比如模板和样式,如果这些东西不需要在子类组件中进行更改。
现在我已经将我的项目移到了角5,这已经行不通了。注释元数据是未定义的。
这是否与AOT编译有关(即使我没有选择该选项)?有人能想到一种方法来恢复这个装饰师过去对角2和角4所做的事情吗?
发布于 2018-02-27 13:51:55
您可以将组件的注释保存在单独的变量中,并与组件一起导出,因此不需要从组件的元数据中检索它。这里有个小例子,希望能对你有所帮助。
https://stackblitz.com/edit/angular-bxbpwr?embed=1&file=app/asignAnnotations.ts
发布于 2017-11-14 07:45:53
您可以通过target['__annotations__'][0]获得注释。
还有'__paramaters__'和'__prop__metadata__',参见decorators.ts的来源
注意:根据角博客,构建优化器现在默认用于生产构建,因此注释在运行时不可用。
免责声明:这是一个黑客和实现细节,所以它不应该使用在生产代码!
https://stackoverflow.com/questions/47234909
复制相似问题