问题描述
我有一些功能,其中有两个单独的组件类,例如类组件A和类组件B。我想在类组件C中进行扩展。
我听说我可以从Angular打字稿的Mixin中寻求帮助,但不确定如何在Component类中使用它。如果有任何方法可以在角度上达到相同的效果,将很有帮助。
我还检查了此处提到的示例: https://stackblitz.com/edit/mixin-example
我还尝试了如下的applyMixins,但无法在Class组件中解决。
class A {
start() {
console.log('Vehicle Started');
}
}
class B {
end() {
console.log('Vehicle stopped');
}
}
class C implements A,B {
end(): void {
throw new Error("Method not implemented.");
}
start(): void {
throw new Error("Method not implemented.");
}
}
applyMixins(C,[A,B])
解决方法
我不太确定您为什么要这样做,但是我设法使其工作: https://stackblitz.com/edit/angular-typescript-mixins
简而言之,我将函数 applyMixins 包装到文件中
export function applyMixins(derivedCtor: any,baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
}
稍后在组件 C 中,我实现了组件 A 和 B ,最后在构造函数中调用了该函数:
export class CComponent implements AComponent,BComponent {
end(): void {
throw new Error("Method not implemented.");
}
start(): void {
throw new Error("Method not implemented.");
}
constructor() {
applyMixins(CComponent,[AComponent,BComponent])
}
}