【发布时间】:2019-09-24 15:58:24
【问题描述】:
这有点类似于在 typescript 中扩展 2 类,但是虽然我设法在 typescript 中做到了,但我在 angular 中找不到正确的方法。
我有一个 Angular 7 应用程序,其中包含 1 个组件、一个服务和一个通用类。
就是这样Stackblitz
我想创建一个从我的类和我的其他组件继承的组件
这是我的 class=>
export class MyClass1<T,O> {
propertyClass1 = "MyClass1"
constructor() {
}
init(value:string){
this.propertyClass1 = value;
}
sayHelloClass(value:string){console.log('class say'+ value)}
}
这里是我的组件 =>
export class MyCom1Component implements OnInit {
propertyComp1 = "MyCom1"
constructor(private service1:Service1Service) {
this.propertyComp1 = service1.getProp();
}
ngOnInit() {
}
sayHelloComponent(value:string){console.log('component say'+ value)}
}
我希望我的孩子可以扩展展位,以便我能够做到
ngOnInit() {
this.sayHelloClass(this.propertyClass1); // class say MyClass1
this.init("hoohoho");
this.sayHelloClass(this.propertyClass1); // class say hoohoho
this.sayHelloComponent(this.propertyComp1); // component say MyCom1
}
我试过的是这个=>
const addMyClassOneInheritance = <T extends new(...args: any[]) => any>(MyCom1Component: T) => {
return class extends MyCom1Component {
constructor(...args: any[]) {
super(...args);
}
};
};
const MyMergedClass = addMyClassOneInheritance(MyClass1);
export class ChildComponent extends MyMergedClass<string,number> {
ngOnInit(){
this.sayHelloClass(this.propertyClass1); // compile ok, execute give a value
this.sayHelloComponent(this.propertyComp1); // compile ok, execute "can't find sayHelloComponent
}
}
编译器没有报错,但是我的组件方法没有被继承
【问题讨论】:
-
我想知道您这样做的目的是什么?因为另一种方法是创建 2 个不同的父类并在子组件中实例化它们。
-
基本上,我讨厌重复的代码,这里有一个类似于我为什么要这样做的解释:prntscr.com/nlcxnd希望你能理解。 serviceForAnimal 共享给所有 Animal,serviceForWolf 共享给所有狼。
-
答案here 可能会对您有所帮助。
-
我设法只使用打字稿来做到这一点,我正在尝试找到一种使用角度组件和默认类的方法
-
我只是想提醒一下,多重继承会带来太多的代码复杂性,因为您已经知道还有其他不违反 DRY 的方式。
标签: angular typescript