如何延长使用依赖注入组件在角2? [英] How to extend a component with dependency injection in Angular 2?
本文介绍了如何延长使用依赖注入组件在角2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类 ModuleWithHttp
:
@Injectable()
export default class {
constructor(private fetchApi: FetchApi) {}
}
和我想用它如下:
@Component({
selector: 'main',
providers: [FetchApi]
})
export default class extends ModuleWithHttp {
onInit() {
this.fetchApi.call();
}
}
这样通过扩展已经注入的依赖我想在它的孩子给它的访问一个超类。
so by extending a super class that already injects a dependency I want to have an access to it in its children.
我试过很多不同的方式,甚至有超一流的组件:
I tried many different ways, even having super-class as a component:
@Component({
providers: [FetchApi]
})
export default class {
constructor(private fetchApi: FetchApi) {}
}
但尽管如此, this.fetchApi
是空
,即使是在超一流的。
But still, this.fetchApi
is null
, even in super-class.
推荐答案
您必须注入fetchAPI在超类和它向下传递给基类
You have to inject fetchAPI in the super class and pass it down to the base class
export default class extends ModuleWithHttp {
constructor(fetchApi: FetchApi) {
super(fetchApi);
}
onInit() {
this.fetchApi.call();
}
}
这是DI是如何工作的,一般的功能。超类将通过继承来实例化基地,但你必须提供所需参数的基础。
This is a feature of how DI works in general. The super class will instantiate the base via inheritance, but you have to supply the required parameters to the base.
这篇关于如何延长使用依赖注入组件在角2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文