在基类中使用依赖项而不必从继承类传递此依赖项

时间:2016-04-07 13:19:51

标签: angularjs typescript angular

在我学习Angular2的过程中,我遇到了以下情况:

  • 1个基类,它使用angular2 / http依赖
  • 1继承扩展基类的类

如何在基类的构造函数中注入angular2 / http依赖项,而不必在实例化继承类时将http作为参数传递。

我不在继承类中使用http,所以我不想在那里看到它!

例如

// base class
class CRUDService {

    // http is used in this service, so I need to inject it here
    constructor(@Inject(Http) http) {}

    findAll() {
        return this.http.get('http://some.api.com/api/some-model');
    }
}

// inheriting class
class ThingService extends CRUDService {

    constructor() {
        // because we extend the base class, we need to call super()
        // this will fail since it expects http as a parameter
        // BUT i don't use http in this class, I don't want to inject it here
        super();
    }
}

理想情况下,我只是在基类中创建一个新的http实例,并像let http = new Http();那样使用它,但这显然不起作用。

1 个答案:

答案 0 :(得分:1)

不支持。如果你想注入一些东西,你必须在子类的构造函数中列出它,如果你想将它传递给超类,你可以使用super(someDependency)。没有办法了。
这不是一个Angular限制,而是一个在类型化类中非常常见的语言限制。