3 回答

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超6個贊
在Angular的最新版本之后,ComponentMetadata類不再可用,這是少數(shù)成員指出的。
這就是我實(shí)現(xiàn)CustomComponent使其工作的方式:
export function CustomComponent(annotation: any) {
return function (target: Function) {
let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
let parentAnnotations = Reflect.getOwnMetadata('annotations', parentTarget);
let parentAnnotation = parentAnnotations[0];
Object.keys(annotation).forEach(key => {
parentAnnotation[key] = annotation[key];
});
};
}
希望能幫助到你!
編輯:前面的代碼塊,即使它起作用,它也會覆蓋擴(kuò)展類的原始元數(shù)據(jù)。在增強(qiáng)版的下面找到它,使您無需修改基類即可擁有多個繼承和覆蓋。
export function ExtendComponent(annotation: any) {
return function (target: Function) {
let currentTarget = target.prototype.constructor;
let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
let parentAnnotations = Reflect.getOwnMetadata('annotations', parentTarget);
Reflect.defineMetadata('annotations', [Object.create(parentAnnotations[0])], currentTarget);
let currentAnnotations = Reflect.getOwnMetadata('annotations', currentTarget);
Object.keys(annotation).forEach(key => {
currentAnnotations[0][key] = annotation[key];
});
};
}

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個贊
如果有人在尋找更新的解決方案,Thierry Templier的答案將是非常完美的。除了ComponentMetadata已被棄用。使用Component反而對我有用。
完整的Custom Decorator CustomDecorator.ts文件如下所示:
import 'zone.js';
import 'reflect-metadata';
import { Component } from '@angular/core';
import { isPresent } from "@angular/platform-browser/src/facade/lang";
export function CustomComponent(annotation: any) {
return function (target: Function) {
var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
var parentAnnotation = parentAnnotations[0];
Object.keys(parentAnnotation).forEach(key => {
if (isPresent(parentAnnotation[key])) {
// verify is annotation typeof function
if(typeof annotation[key] === 'function'){
annotation[key] = annotation[key].call(this, parentAnnotation[key]);
}else if(
// force override in annotation base
!isPresent(annotation[key])
){
annotation[key] = parentAnnotation[key];
}
}
});
var metadata = new Component(annotation);
Reflect.defineMetadata('annotations', [ metadata ], target);
}
}
然后將其導(dǎo)入到您的新組件sub-component.component.ts文件中,并使用@CustomComponent而不是@Component這樣:
import { CustomComponent } from './CustomDecorator';
import { AbstractComponent } from 'path/to/file';
...
@CustomComponent({
selector: 'subcomponent'
})
export class SubComponent extends AbstractComponent {
constructor() {
super();
}
// Add new logic here!
}
- 3 回答
- 0 關(guān)注
- 746 瀏覽
添加回答
舉報(bào)