如何使用服务依赖项定义Angular类层次结构

时间:2018-10-26 00:41:22

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

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

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

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

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

到目前为止,所有这些对我来说都是合乎逻辑的,我可以使其正常工作。

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

因此,在我的Variation类中,我必须包括以下几行内容:

Adjustment

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

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

export class Variation extends Adjustment { .... constructor( afs: AngularFirestore, .... ) {} super (afs, ....) 类实际上不需要了解有关AngularFirestore的任何信息,但我必须将其注入该类中才能使其被注入Variation类中。

必须有一种避免这种情况的方法,但我只是想不通。

1 个答案:

答案 0 :(得分:0)

编辑

我用以下内容替换了以前的答案:

我对注射器进行了更多研究,并找到了答案: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()
  }
}

这样,我们可以使用服务,而不必在构造函数中声明它。

相关问题