Angular 7:覆盖第三方组件的父类



我必须使用第三方库的许多组件,这些组件都扩展了一个抽象类,我必须改变这些行为。若要使其更清晰,请参阅以下示例代码行:

abstract class ThirdPartyParentClass {
parentMethod() {
// I need to alter this method...
}
}
class ThirdPartyComponent1 extends ThirdPartyParentClass {
componentMethod() {
parentMethod();  // ...because it gets called here...
}
}
class ThirdPartyComponent2 extends ThirdPartyParentClass {
componentMethod() {
parentMethod();  // ...and here...
}
}
// ...and in a few other places.

一个明显的解决方案是扩展父类,覆盖相应的方法,并复制其所有组件的代码,使它们扩展我的自定义父类。但是,由于第三方库目前正在大量开发中,我担心这样做会引入很多技术债务。

还有没有其他可能达到这个目标?

我认为这是一个很好的组合
用例 创建自己的类并创建自定义方法:

export class MyCustomImplementation {
parentMethod() {
// this is the parentMethod altered
}
}

创建并导出一个函数以将mixin应用于您的类:

export function applyMixins(derived: any, bases: any[]) {
bases.forEach((base) => {
Object.getOwnPropertyNames(base.prototype)
.filter((propertyName) => propertyName.toLowerCase() !== 'constructor')
.forEach((propertyName) => {
derived.prototype[propertyName] = base.prototype[propertyName];
});
});
}

在第三方组件中,导入并实现您的类:

class ThirdPartyComponent1 extends ThirdPartyParentClass, implements MyCustonImplementation {
constructor() {
super();
applyMixins(ThirdPartyComponent1, [MyCustomImplementation]);
}
componentMethod() {
parentMethod();  // ...because it gets called here...
}
}

这样,您就不会更改第三方组件和第三方类之间的紧密耦合继承关系,但可以覆盖该方法。

我做了一个虚拟的堆栈闪电战实现

假设父类或子类是可注入的,您应该能够使用类提供程序: https://angular.io/guide/dependency-injection-providers#aliased-class-providers

当父类是可注入的并且通过构造函数注入其他第三方类时,您可以扩展父类,覆盖该方法,然后将模块配置为使用您的类而不是第三方父类。

当第三方子类是可注入的时,您必须扩展所有子类并覆盖父方法。之后,配置模块。

最新更新