【发布时间】: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