我正在使用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/await
或watch
吗?我将如何实施呢?
任何帮助将不胜感激。
由于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'
},
}
});
});
}