【问题标题】:Need to execute all functions before executing another function - Angular需要在执行另一个函数之前执行所有函数 - Angular
【发布时间】:2021-09-13 09:23:25
【问题描述】:

我有 5 个函数可以返回数据。在执行第 6 个函数之前,我必须执行所有这些函数。目前,在所有 5 个函数返回数据之前,它正在执行第 6 个函数。这只是第一次发生。第二次,当第 6 个函数执行时,它具有来自 5 个函数的所有数据。

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();
    }
  }

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    您可以使用 RxJS forkJoin 函数链接所有函数(应该返回可观察对象而不是在其中订阅)来实现这一点。

    尝试以下方法:

    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$)
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      相关资源
      最近更新 更多