2

我遇到了奇怪的情况,想讨论它是否正确。(也请在最后寻找小问题更新)

在 Angular 4.3 中,我有一些抽象类,它由几个 Angular 组件扩展。看起来像:

export abstract class SidePanel {
  protected prop1;
  protected prop2;

  protected method1() {
    //...
  };
}

@Component({
 // ...
})
export class SidePanelOne extends SidePanel {
 // body
}

@Component({
 // ...
})
export class SidePanelTwo extends SidePanel {
 // body
}

我想在父类 SidePanel 中添加一些通用功能,这需要 angular 的 Injector 可以访问。所以我想做这样的事情:

export abstract class SidePanel {
  protected prop1;
  protected prop2;

  constructor(injector: Injector){
    this.prop1 = injector.get(MyClassName);
  }

  protected method1() {
    //...
  };
}

为了使它成为可能,我可以从孩子那里传递 Injector:

@Component({
 // ...
})
export class SidePanelOne extends SidePanel {
 constructor(injector: Injector) {
   super(injector);
 }

 //rest of body
}

但我不想这样做,因为我有太多孩子,在这种情况下,我不得不在所有这些中添加 Injector。所以我找到了简单的解决方案(但不确定它是否正确):

@Injectable()
export abstract class SidePanel {
  protected prop1;
  protected prop2;

  constructor(injector: Injector){
    this.prop1 = injector.get(MyClassName);
  }

  protected method1() {
    //...
  };
}

@Component({
 // ...
})
export class SidePanelOne extends SidePanel {
  private test() {
    this.prop1.myClassMethod(); // works!
  }

 // rest of body
}

因此,我的子类(组件)不必拥有自己的构造函数,只需注入和传递 Injector 即可,一切正常。但是在抽象类上应用 Injectable() 装饰器看起来很奇怪。

正确与否?

提前感谢您的意见。

更新 14.03:

事实证明,对于上述情况,可以使用“空”组件装饰器而不是 Injectable:

@Component({})
export abstract class SidePanel {
  // body
}

这也令人困惑:元数据为空的组件意味着什么,使用它是否正确以及为什么所有参数都是可选的(甚至是选择器)?

4

0 回答 0