[API数据直到检查元素或调整页面大小后才加载到chart.js中

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

我正在使用Chart.js和此API在澳大利亚创建covid-19案例的折线图。但是,直到执行诸如检查页面上的元素或调整窗口大小之类的操作时,API数据才会加载到图表中。

这是我的JS文件:

window.onload = function() {
   let dates = [];
   let confirmedCases = [];
   let confirmedRecovered = [];
   let confirmedDeaths = [];

   function addArrayFunc(date, confirmed, recovered, deaths) {
      dates.push(date);
      confirmedCases.push(confirmed);
      confirmedRecovered.push(recovered);
      confirmedDeaths.push(deaths);
   }
   fetch("https://pomber.github.io/covid19/timeseries.json")
      .then(response => response.json())
      .then(cases => {
         cases["Australia"].forEach(({
               date,
               confirmed,
               recovered,
               deaths
            }) =>
            addArrayFunc(date, confirmed, recovered, deaths)
         )
      })

   const ctx = document.getElementById('myChart').getContext('2d');
   new Chart(ctx, {
      type: 'line',
      data: {
         labels: dates,
         datasets: [{
               label: 'Confirmed',
               borderColor: 'pink',
               backgroundColor: 'pink',
               fill: 'false',
               data: confirmedCases
            },
            {
               label: 'Recovered',
               borderColor: 'blue',
               backgroundColor: 'blue',
               fill: 'false',
               data: confirmedRecovered
            },
            {
               label: 'Deaths',
               borderColor: 'green',
               backgroundColor: 'green',
               fill: 'false',
               data: confirmedDeaths
            }
         ]
      },
      options: {
         responsive: true,
         title: {
            display: true,
            text: 'Covid-19 Cases in Australia'
         },
      }
   });
}

这是我的html文件:

<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Confirmed Covid-19 cases in Australia</title>
      <style>
         canvas {
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            width: 75%;
         }
      </style>
      <script src="script.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
   </head>
   <body>
      <canvas id="myChart"></canvas>
   </body>
</html>

我相信我是在从URL到达数据之前创建图表的,但是我不知道必须对此进行更正。这可以解决async/awaitwatch吗?我将如何实施呢?

任何帮助将不胜感激。

javascript api async-await chart.js watch
1个回答
1
投票

由于fetch进行了异步调用,因此您需要在收到响应后创建图表。因此,只需将图表创建代码放在fetch内,它将如下所示工作。

.then
window.onload = function() {
  let dates = [];
  let confirmedCases = [];
  let confirmedRecovered = [];
  let confirmedDeaths = [];

  function addArrayFunc(date, confirmed, recovered, deaths) {
    dates.push(date);
    confirmedCases.push(confirmed);
    confirmedRecovered.push(recovered);
    confirmedDeaths.push(deaths);
  }

  fetch("https://pomber.github.io/covid19/timeseries.json")
    .then(response => response.json())
    .then(cases => {
      cases["Australia"].forEach(({
          date,
          confirmed,
          recovered,
          deaths
        }) =>
        addArrayFunc(date, confirmed, recovered, deaths)
      )
      new Chart(document.getElementById('myChart'), {
        type: 'line',
        data: {
          labels: dates,
          datasets: [{
              label: 'Confirmed',
              borderColor: 'pink',
              backgroundColor: 'pink',
              fill: 'false',
              data: confirmedCases
            },
            {
              label: 'Recovered',
              borderColor: 'blue',
              backgroundColor: 'blue',
              fill: 'false',
              data: confirmedRecovered
            },
            {
              label: 'Deaths',
              borderColor: 'green',
              backgroundColor: 'green',
              fill: 'false',
              data: confirmedDeaths
            }
          ]
        },
        options: {
          responsive: true,
          title: {
            display: true,
            text: 'Covid-19 Cases in Australia'
          },
        }
      });
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.