angular - 使用不同的构造函数以 Angular 继承两个组件

标签 angular typescript

这有点类似于在 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

注释使该类对 DI 可用

然后照常扩展您的父组件:ChildComponent extend MyCom1Component 并使用 ChildComponent 的构造函数注入(inject)您的 MyClass1 最后用您刚刚注入(inject)的类的实例调用父类的构造函数。

constructor(public myclass1: MyClass1) {
    super(myclass1);
  }

关于angular - 使用不同的构造函数以 Angular 继承两个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56014960/

相关文章:

Angular 2选择选项默认值

angular - 传单标记点击始终显示最后一个元素

javascript - 如何在 Angular2 中保护我的代码?

javascript - Fade in Text Animation 根本不出现

typescript - 具有多个类型参数的泛型中的推断类型

node.js - 如何替换图像Node.JS中除黑色以外的所有颜色

angular - Redux 状态缺少来自 redux offline 的 "offline"部分

angular - 如何在 Angular 中的 HTTP post 请求中传递 url 中的查询参数

mysql - 如何在第三方模块上添加自定义类型?

javascript - 等待带有定位器的元素时超时