如何使用依赖注入扩展组件? [英] How to extend a component with dependency injection?
问题描述
我有以下课程ModuleWithHttp
:
@Injectable()
export default class {
constructor(private fetchApi: FetchApi) {}
}
我想按如下方式使用它:
and I want to use it as follows:
@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
仍然是null
.
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 child 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 child via inheritance, but you have to supply the required parameters to the child.
这篇关于如何使用依赖注入扩展组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!