Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is for

    fetch('http://127.0.0.1:8000/api/salesChart')
        .then(response => response.json())
        .then(data => {
            this.sales = data.sales;
             console.log(sales);
         });

Google CHart Code

<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
    var data = new google.visualization.DataTable();
    sales[0].forEach(element => {
        console.log(element)
        if(element === "Month")
            data.addColumn('string', element);
        else
            data.addColumn('number', element);
    });
    sales.splice(0,1)
    data.addRows(sales)
    var options = {
        chart: {
            title:'Sales Chart'+ '('+ start +'-'+to + ')'
        },
        width: 600,
        height: 500,
        vAxis:{title: 'Quantity (MT)',viewWindow: {min: 0},format:'# MT'},
    };

    var chart = new google.charts.Line(document.getElementById('curve_chart'));
    chart.draw(data, google.charts.Line.convertOptions(options));
}

But when id console.log(sales) Below images data will come like this.and sometimes graph will come and sometimes throws errors

enter image description here

Error

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
321 views
Welcome To Ask or Share your Answers For Others

1 Answer

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));
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...