首页 > 解决方案 > 如何在第三个组件类中扩展两个 Angular 类组件?

问题描述

我有一些功能我有两个单独的组件类,例如类组件 A 和类组件 B。我想扩展类组件 C 中的那些。

我听说我可以在 Angular typescript 中从 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])

标签: angulartypescriptinheritanceangular5mixins

解决方案


我不太确定你为什么要这样做,但我设法让它工作: 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中,我实现了组件AB,最后在构造函数中调用了该函数:

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])
    }
}

推荐阅读