为什么 Angular 函数不等待 HighChart 的数据加载?

Why Angular function does not wait for the data load for HighChart?

下面是代码,我也试过异步/等待但没有按预期工作,我总是在 getCharts() 函数的 this.totalTwoChartData 中得到未定义的值? 我可以期待空值但不是未定义的.. 我应该只涵盖一个功能吗?还是承诺是最好的方式? 编写干净代码和处理这些类型情况的最佳做法是什么?

ngOnInit(): void {
    this.getAllChartData()
  }

  // Get all chart data
  getAllChartData() {
    // Do not call server api if callStartDate / callEndDates is null
    if (this.calStartDate !== null && this.calEndDate !== null) {
      this.getOneChartData();
      this.getTwoChartData();
      this.getThreeChartData();
      this.getCharts();
    }
  }

  // One chart data
  getOneChartData() {
    this.oneChartSubscription = this.chartService
      .getOneChartService(this.calStartDate, this.calEndDate)
      .pipe(filter((res) => res !== null))
      .subscribe((response) => {
        this.totalOneChartData = response.data
      })
  }

  // Two chart data
  async getTwoChartData() {
    this.twoChartSubscription = this.chartService
      .getTwoChartService(this.calStartDate, this.calEndDate)
      .pipe(filter((res) => res !== null))
      .subscribe((response) => {
        this.totalTwoChartData = response.data
      })
  }

  // Three chart data
  getThreeChartData() {
    this.threeChartSubscription = this.chartService
      .getThreeChartService(this.calStartDate, this.calEndDate)
      .pipe(filter((res) => res !== null))
      .subscribe((response) => {
        this.totalThreeChartData = response.data
      })
  }


  async getCharts() {
    // Load Two chart data
    if (await this.totalTwoChartData !== null) {
      var objOneChart = await this.totalOneChartData;
      this.arrOneName = Object.keys(objOneChart).map((k) => {
        return objOneChart[k]['Name'];
      });

      this.arrOneAmt = Object.keys(objOneChart).map((k) => {
        return parseFloat(objOneChart[k]['receivedAmount']);
      })....


这是 forkJoin 函数的 use-case(或基于 use-case 的 combineLatestzip)并行触发所有可观察对象并在它们发出后继续。

有关详细信息,请参阅

如果您再次尝试在控制器(*.ts 文件)中的其他地方同步使用变量 this.arrOneNamethis.arrOneAmt,那么您实际上需要将订阅移动到那个地方。根据经验,在需要发射的地方订阅 observables。

getCharts() {
  forkJoin({
    oneChartData: this.chartService.getOneChartService(this.calStartDate, this.calEndDate).pipe(filter(res => !!res)),
    twoChartData: this.chartService.getTwoChartService(this.calStartDate, this.calEndDate).pipe(filter(res => !!res)),
    threeChartData: this.chartService.getThreeChartService(this.calStartDate, this.calEndDate).pipe(filter(res => !!res)),
  }).subscribe({
    next: (data: any) => {
      this.arrOneName = Object.keys(data.oneChartData).map((k) => objOneChart[k]['Name']);
      this.arrOneAmt = Object.keys(data.oneChartData).map((k) => parseFloat(objOneChart[k]['receivedAmount']));
      },
    error: (error: any) => {
      // handle error
    }
  });
}