【问题标题】:Why does a superclass requires services from subclass in Angular?为什么超类需要 Angular 中子类的服务?
【发布时间】:2022-11-18 15:05:36
【问题描述】:

今天我在 Angular 中看到了这段代码

export class ContentFormComponent extends FormBase {

...

constructor(
  private authService: AuthService,
  private apiService: ApiService,
  private segmentService: SegmentService
) { super(authService, segmentService) }

...

}

超类 FormBaseComponent 声明如下所示:

export abstract class FormBase {

...

constructor (
   protected authService: AuthService,
   protected segmentService: SegmentService
) { }

...

}

我的问题是,为什么这个抽象类需要子类的服务? 我的理解是 Angular 中的服务是单例的,这意味着整个应用程序中只存在一个服务实例。此外,这两种服务都是在 root 中提供的。

为什么 FormBase 类不能简单地通过 DI 在构造函数定义中注入这些服务?这不是多余的吗?

请温柔点,我对这一切都很陌生,我只是想学习 哈哈

【问题讨论】:

  • 构造函数不是这样工作的:当一个类被子类化时,子类就成为超类构造函数的看门人,并且全部超类的依赖关系现在必须通过子类。

标签: angular typescript oop dependency-injection frontend


【解决方案1】:

问题的实际答案请参考戴先生的评论。

构造函数不是这样工作的:当一个类被子类化时,子类就成为超类构造函数的看门人,所有超类的依赖项现在都必须通过子类。

我的回答是为您提供一种无需将这些服务传递给父母的方法。这种方法是可能的角度 14.

在这里您可以将服务的注入移动到在构造函数之外注入功能。因此,子类不需要处理这些服务即可通过。

export abstract class FormBase {
  protected authService: AuthService = inject(AuthService);
  protected segmentService: SegmentService = inject(SegmentService);
}

export class ContentFormComponent extends FormBase {
  constructor(
    private apiService: ApiService
  ) { super(); }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 2014-04-23
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多