我有一个只需调用一次的 HTTP 函数,并且所有子组件都依赖于该函数。所以我从父组件调用这个函数。
现在,在任何子组件的 ngOnInit 中进行任何调用之前,我需要检查父函数是否成功执行,否则等待父函数从 http 调用(服务器)返回响应:
- Parent Component
- Child Component 1
- Child Component 2
- Child Component 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,那么所有问题都会得到解决,效果会更好:
// Parent component:
main(): void {
this.backendService.main().subscribe(res => {
this.sharedDataService.setParentData(res);
this.data = res;
});
}
// Child components:
ngOnInit(): void {
this.sharedDataService.getParentData().subscribe(parentData => {
this.backendService.child(parentData).subscribe(res => this.childData = res);
});
}
// Your shared service:
export class SharedDataService {
private parentData: BehaviorSubject<any> = new BehaviorSubject({});
setParentData(data): void {
this.parentData.next(data);
}
getParentData(): Observable<any> {
return this.parentData.asObservable();
}
}
关于angular - 只有在父组件中的函数完成后才调用子组件中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45076355/