角度列表包含元素,但长度为0

我使用以下代码发出http get请求,如下所示

export class Covid19Service {
  baseUrl = 'https://api.covid19api.com/';

  constructor(private http: HttpClient) { }

  getSummary() {
    return this.http.get(this.baseUrl + 'summary').subscribe(data => {
      console.log(data);
    });
  }

  getCountry() {
    return this.http.get(this.baseUrl + 'dayone/country/ie/status/confirmed');
  }

}

然后,我将数据解析到getCountry()方法的列表中

export class BarchartComponent implements OnInit {
  dailyTotalConfirmed: number[] = [];
  dailyNewConfirmed: number[] = [];

  constructor(private covid19: Covid19Service) { }

  ngOnInit() {
    this.getCountry();
    this.calculateDailyNewConfirmed();
    console.log(this.dailyTotalConfirmed);
    console.log(this.dailyNewConfirmed);
  }

  getSummary() {
    return this.covid19.getSummary();
  }

  getCountry() {
    this.covid19.getCountry()
    .subscribe(data => {
      const covid = Object.keys(data);

      for (const key of covid) {
        const cases = data[key].Cases;
        this.dailyTotalConfirmed.push(cases);
      }
    });
  }

  calculateDailyNewConfirmed() {
    const data = this.dailyTotalConfirmed;

    for (let i = 0; i < data.length - 1; i++) {
      const casesToday = data[i];
      const casesTomorrow = data[i + 1];

      this.dailyNewConfirmed.push(Math.abs(casesTomorrow - casesToday));
    }
  }

}

当调用calculateDailyNew()方法时,该方法内的for循环不会执行,因为列表的长度为0,即使在我console.log()列表时,列表中也有元素。 我做错了什么?

评论