【问题标题】:How to define Angular class hierarchy with service dependencies如何使用服务依赖项定义 Angular 类层次结构
【发布时间】:2018-10-26 00:41:22
【问题描述】:

我的头在这上面转了一圈。

我想创建类来表示从 Angular(不是 AngularJS)后端返回的数据。

我有两个顶级课程VariationReallocation。两者都是基类Adjustment 的类型。因此VariationReallocation 扩展 Adjustment。大多数类定义都在Adjustment 类中,两个派生类之间只有很小但很重要的区别。

使用Adjustment 类来处理与后端的大部分通信似乎很有意义。也就是说,假设我想得到一个Variation。我应该能够将 id 传递给 VariationgetAdjustment 方法,并让它返回一个填充了来自服务器的数据的 Variation 实例。

到目前为止,这一切对我来说都是合乎逻辑的,我可以让它发挥作用。

问题是我必须使用服务从后端获取数据。我碰巧正在使用 AngularFirestore 来获取数据。

所以,在我的Adjustment 类中,我必须包含一个构造函数,如下所示:

constructor(
     public afs: AngularFirestore,
     ....){}

然后问题是当我在派生类中使用 super() 时。我还必须将 AngularFirestore 注入派生类。也就是说,我必须有类似的东西:

export class Variation extends Adjustment {
....
constructor(
    afs: AngularFirestore,
    .... ) {}
super (afs,
        ....)

Variation 类实际上并不需要了解有关 AngularFirestore 的任何信息,但我必须将其注入此类以使其能够注入到 Adjustment 类中。

一定有办法避免这种情况,但我就是想不通。

【问题讨论】:

  • 我不认为有办法解决这个问题,但如果有的话,我很想看看 :)
  • 我也不得不这样做。如果属性注入可用,也许它可以做不同的事情,但现在你已经通过了构造函数,所以我看不到另一种方式。
  • 感谢您的 cmets。至少我没有遗漏一些非常明显的东西。

标签: angular service dependency-injection model class-hierarchy


【解决方案1】:

编辑

我已将之前的答案替换为以下内容:

我对注射器进行了更多研究,并找到了这个答案:https://stackoverflow.com/a/37482645/5348742

我们知道 Angular 维护着一个应用程序范围的注入器。我们可以通过在我们需要的任何模块级别创建Injector 类型的属性来访问这个注入器。如果我们在root注册了服务,我们可以在app.module获取注入器。

这样,我们就不用在构造函数中获取服务的注入器了。

我们在app.module 中获得对服务的引用,将其导出,然后在需要的任何地方使用它。

查看上面的链接以获取有关获取服务参考的更多详细信息。

就在应用程序的其他地方使用它而言,它是这样的。

app.module

...

export let myService: MyService;

export class AppModule {

constructor(private router: Router,
        private injector: Injector){
        appInjector = this.injector;
        myService = appInjector.get(MyService)
  }
}

然后在你要使用的组件或类中:

import { myService } from 'app.module'

...

export class MyClass {

constructor(...){...}

  getSomething(){
    const something = myService.doSomething()
  }
}

通过这种方式,我们可以使用服务而无需在构造函数中声明它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2013-12-25
    • 2019-02-03
    相关资源
    最近更新 更多