这有点类似于在 typescript 中扩展 2 类,但是尽管我设法在 typescript 中做到了,但我在 angular 中找不到正确的方法。
我有一个包含 1 个组件、一个服务和一个通用类的 Angular 7 应用。
就是这样Stackblitz
我想制作一个继承 self 的类和其他组件的组件
这是我的课=>
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)}
}
我希望我的 child 能扩展摊位,这样我就可以做到
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
}
编译器没有报错,但是我的组件方法没有被继承
最佳答案
我建议采用不同的方法。
通过使用 @Injectable
然后照常扩展您的父组件:ChildComponent extend MyCom1Component
并使用 ChildComponent
的构造函数注入(inject)您的 MyClass1
最后用您刚刚注入(inject)的类的实例调用父类的构造函数。
constructor(public myclass1: MyClass1) {
super(myclass1);
}
关于angular - 使用不同的构造函数以 Angular 继承两个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56014960/