从api获取数据后创建Chart.js

问题描述 投票:0回答:1

我在Angular中有两个功能:

从Web服务获取一些数据并将其存储在this.apiDaythis.apiDayLabel变量中:

getDayScan() {
    this.btcPriceService.getDailyBTCScan().subscribe(data => {
      data.Data.Data.forEach(price => {
        this.apiDay.push(price.open);
        this.apiDayLabel.push(new Date(price.time * 1000).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}));
      });
    });
}

并且使用this.apiDaythis.apiDayLabel中的数据创建一个chartjs:

public createDay(defaultChartConfig: any) {

    this.canvas = document.getElementById('dayChart');
    this.ctx = this.canvas.getContext('2d');

    const dataTotal = {
      // Total Shipments
      labels: this.apiDayLabel,
      datasets: [{
        label: 'Price',
        fill: true,
        backgroundColor: this.bgColorSelector(this.apiDay),
        borderColor: this.borderColorSelector(this.apiDay),
        borderWidth: 2,
        borderDash: [],
        borderDashOffset: 0.0,
        pointBackgroundColor: this.borderColorSelector(this.apiDay),
        pointBorderColor: 'rgba(255,255,255,0)',
        pointHoverBackgroundColor: this.borderColorSelector(this.apiDay),
        pointBorderWidth: 20,
        pointHoverRadius: 4,
        pointHoverBorderWidth: 15,
        pointRadius: 0,
        data: this.apiDay,
      }]
    };

    this.myChartDay = new Chart(this.ctx, {
      type: 'lineWithLine',
      data: dataTotal,
      options: defaultChartConfig
    });
  }

我在ngOnInit()函数中这样调用这两个函数:

ngOnInit() {
    this.getDayScan();
    this.createDay(defaultChartConfig);
}

我的问题是图表是在我从api获取数据之前创建的。

是否有办法等待数据在那里然后开始创建图表?

像这样(伪代码)

public createDay(defaultChartConfig: any) {

    getDayScan();

    // wait for it to finish so every necessary variable is declared
    // and only THEN go on with the other code 

    this.canvas = document.getElementById('dayChart');
    this.ctx = this.canvas.getContext('2d');

    ...

}

所以我只需要在createDay中调用ngOnInit函数

或者在这种情况下最佳做法是什么?

javascript angular typescript web-services chart.js
1个回答
0
投票

我建议您使用async await等待api响应。

© www.soinside.com 2019 - 2024. All rights reserved.