Search code examples
angularrxjsobservableangular2-http

Call function in child component only after function in parent component is completed


I have an HTTP function that needs to be called only once and all child components are dependent on this function. So I am making this function call from parent component.

Now before making any call in ngOnInit of any of the child component I need to check whether parent function is successfully executed else wait until parent function gets response back from http call (server):

  • Parent Component
    • Child Component 1
    • Child Component 2
    • Child Component 3

Parent component making call to service function
Child component must wait until parent function is executed

Parent Component

main(): void {
    this.backendService.main().subscribe(res => {
        this.sharedDataService.setParentData(res);
        this.data = res;
    });
}

ngOnInit(): void {
    this.main();
}

Child Component

child(): void {
    let parentData = this.sharedDataService.getParentData();
    this.backendService.child(parentData).subscribe(res => this.childData = res);
}

ngOnInit(): void {
    this.child();
}

backendService - makes http calls
sharedDataService - has data which is shared across all components

But this.backendService.child function gets called even before this.backendService.main function http call receives response. Is there any way to achieve this?


Solution

  • Because you're using a shared service, it will be better, with all your problem solved, if you use 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();
        }
    }