KillMonger
KillMonger

Reputation: 29

Need to execute all functions before executing another function - Angular

I have 5 functions which will return data. I have to execute all these functions before executing the 6 th function. Currently, it is executing the 6th func before all 5 functions return data. This happens only the first time. The second time,when 6 th function is executing,it has all the data from the 5 functions.

ngOnInit()
{   this.getTitle();                     //func 1
    this.getNation();                  
    this.getGender();                        
    this.getPass();
    this.getPax();                       //func 5
    this.patchFormValue();               //func 6
}



  private getTitle() {                 // 5  similar functions that return data
    this._addNewPassengerService.getTitle()
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe(
        resData => {
          this.titleData = resData || [];
          this._changeDetector.detectChanges();
        }
      );
  }


  private patchFormValue() {
    const data = this.data.passengerDetails;
    if (data && this.titleData && this.nationData
      && this.paxData &&this.genderData && this.passengerData) {       
    this.addPassengersFormGroup.controls.passengerFormArray['controls'].forEach(group => 
      {
        group.patchValue(data);
      });

      this._changeDetector.detectChanges();
    }
  }

Upvotes: 0

Views: 606

Answers (1)

Amer
Amer

Reputation: 6716

You can achieve that using the RxJS forkJoin function to chain all the functions (which should return observables instead of subscribing within them).

Try the following:

ngOnInit() {
  forkJoin([
    this.getTitle(),
    this.getNation(),
    this.getGender(),
    this.getPass(),
    this.getPax(),
  ]).subscribe(() => {
    // here you can call the 6th function or anything else, since all the other functions (observables) have been completed
    this.patchFormValue(); //func 6
  });
}

// The functions (except 6th should return Observable to be cahined together using `forkJoin`)
private getTitle(): Observable<any> {
  // 5  similar functions that return data
  this._addNewPassengerService.getTitle().pipe(
    tap((resData) => {
      // handle the resData here instead of `subscribe`
      this.titleData = resData || [];
      this._changeDetector.detectChanges();
    }),
    takeUntil(this.componentDestroyed$)
  );
}

Upvotes: 2

Related Questions