Angular 角度7:覆盖第三方组件的父类
我必须使用第三方库的许多组件,这些组件都扩展了一个抽象类,我必须改变抽象类的行为。要使其更清楚,请参见以下示例代码行:Angular 角度7:覆盖第三方组件的父类,angular,typescript,Angular,Typescript,我必须使用第三方库的许多组件,这些组件都扩展了一个抽象类,我必须改变抽象类的行为。要使其更清楚,请参见以下示例代码行: 抽象类第三方ParentClass{ 父方法(){ //我需要改变这个方法。。。 } } 类ThirdPartyComponent1扩展了ThirdPartyParentClass{ 组件方法(){ parentMethod();/…因为它在这里被调用。。。 } } 类ThirdPartyComponent2扩展了ThirdPartyParentClass{ 组件方法(){ p
抽象类第三方ParentClass{
父方法(){
//我需要改变这个方法。。。
}
}
类ThirdPartyComponent1扩展了ThirdPartyParentClass{
组件方法(){
parentMethod();/…因为它在这里被调用。。。
}
}
类ThirdPartyComponent2扩展了ThirdPartyParentClass{
组件方法(){
parentMethod();/…这里。。。
}
}
//…还有其他一些地方。
一个显而易见的解决方案是扩展父类,覆盖相应的方法,并复制其所有组件的代码,使它们扩展我的自定义父类。然而,由于第三方库目前正在进行大量开发,我担心这样做会带来很多技术债务
是否还有其他可能实现此目标?假设父类或子类是可注入的,您应该能够使用类提供程序: 当父类是可注入的并且通过其他第三方类中的构造函数注入时,您可以扩展父类,覆盖该方法,然后将模块配置为使用您的类而不是三方父类
当第三方子类是可注入的时,您必须扩展所有子类并覆盖父方法。然后配置您的模块。我认为这是
创建自己的类并创建自定义方法:
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...
}
}
在第三方组件中,导入并实现类:
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...
}
}
这样,您就不会更改ThirdPartyComponents和ThirdPartyClass之间的紧耦合继承关系,但可以覆盖该方法
我做了一个这是一个非常好的方法!非常感谢你!然而,在我的特殊情况下,第三方组件1是第三方组件。更准确地说,我有一些第三方组件,它们都扩展了父类并调用了这个特定的方法。因此,通过使用您的方法,我要么复制所有组件(这将引入大量技术债务),要么扩展它们。但是,在扩展的情况下,我不确定应该如何使用这种方法来更改组件的祖父母的方法。@georg un:我修改了stackblitz。我创建了一个服务,您可以在其中覆盖第三方组件的方法,而无需创建自定义组件。哇,这是一个很棒且优雅的解决方案!我用它来覆盖父类的方法,它就像一个符咒。非常非常感谢!我看到的唯一缺点是,如果他们更改了要覆盖的方法的名称,您不会注意到,它仍然会编译,并且在运行时不会出现任何错误。我不知道它是否会出现,如果是这样,我会检查自定义方法是否仍然是组件的一部分。如果不是,我会抛出一个错误,使应用程序快速而响亮地失败。我很高兴这有帮助!:)