【发布时间】:2017-12-17 23:36:58
【问题描述】:
我有一个只需要调用一次的 HTTP 函数,所有子组件都依赖于这个函数。所以我从父组件调用这个函数。
现在在任何子组件的 ngOnInit 中进行任何调用之前,我需要检查父函数是否成功执行,否则等到父函数从 http 调用(服务器)获得响应:
- 父组件
- 子组件 1
- 子组件 2
- 子组件 3
父组件调用服务函数
子组件必须等到父函数执行完毕
父组件
main(): void {
this.backendService.main().subscribe(res => {
this.sharedDataService.setParentData(res);
this.data = res;
});
}
ngOnInit(): void {
this.main();
}
子组件
child(): void {
let parentData = this.sharedDataService.getParentData();
this.backendService.child(parentData).subscribe(res => this.childData = res);
}
ngOnInit(): void {
this.child();
}
backendService - 进行 http 调用
sharedDataService - 具有在所有组件之间共享的数据
但是 this.backendService.child 函数甚至在 this.backendService.main 函数 http 调用收到响应之前就被调用了。有什么方法可以实现吗?
【问题讨论】:
-
为什么不从共享数据服务中公开一个 observable,它会在操作完成时发出?
this.sharedDataService.completed$.subscribe(() => this.backendService...)。或者使用| async解析父组件中的数据,并使其成为子组件的@Input。 -
不要在 ngOnInit 上调用
this.child(),你应该在 parentComponent 中使用 eventEmitter 并在子组件中监听事件,收到事件后你必须调用this.child()这里是一个例子 sitepoint.com/angular-2-components-inputs-outputs -
@jonrsharpe 感谢您的指导。让我试试。
-
@nivas 谢谢你的建议
标签: angular rxjs observable angular2-http