both google's load
method and the fetch
method run asynchronously,
so you have to wait until both have completed before trying to draw the chart.
you could use something similar to the following...
load google charts, then fetch the data, then draw the chart...
google.charts.load('current', {
packages: ['line']
}).then(function () {
var chart = new google.charts.Line(document.getElementById('curve_chart'));
var options = {
chart: {
title:'Sales Chart'+ '('+ start +'-'+to + ')'
},
width: 600,
height: 500,
vAxis:{title: 'Quantity (MT)',viewWindow: {min: 0},format:'# MT'},
};
fetch('http://127.0.0.1:8000/api/salesChart')
.then(response => response.json())
.then(data => {
var dataTable = new google.visualization.DataTable();
data.sales[0].forEach(element => {
if(element === "Month")
dataTable.addColumn('string', element);
else
dataTable.addColumn('number', element);
});
data.sales.splice(0,1)
dataTable.addRows(data.sales)
chart.draw(dataTable, google.charts.Line.convertOptions(options));
});
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…