【问题标题】:Use dependency in base class without having to pass this dependency from inheriting class [duplicate]在基类中使用依赖项,而不必从继承类传递此依赖项[重复]
【发布时间】:2016-07-28 09:52:10
【问题描述】:

在学习 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(); 那样使用它,但这显然行不通。

【问题讨论】:

  • 您需要将其注入到继承类中,但如果有帮助,您可以从基类访问它,执行类似(<any> this).http.get(...) 的操作(您不需要通过@987654324 显式传递它@.

标签: angularjs typescript angular


【解决方案1】:

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

【讨论】:

  • 我正试图解决这个问题。在这个关键时刻,这对我来说似乎非常荒谬...... :(
  • 我听说过很多。 Angular 对此无能为力,这就是 TS(和许多其他语言)中的构造函数的工作方式。如果子类根本没有构造函数,则使用超类的构造函数,但如果子类有构造函数,则所有参数都需要重复传递给super()
猜你喜欢
  • 1970-01-01
  • 2019-12-19
  • 2021-01-21
  • 2013-09-03
  • 2016-06-10
  • 1970-01-01
  • 2021-02-12
  • 2023-03-05
  • 1970-01-01
相关资源
最近更新 更多