Data from api not showing in chart.js (angular)

๐Ÿ‘:-1

What your doing is that you read the data before it is there.

get_project():void{
  return this.projectService.get_project(1)
}

ngOnInit() {
    this.get_project().subscribe(data=>{
        this.visitor=data.visitor;
        console.log(data.visitor);
        this.chart(); // only when the data is fetched, you can render chart
    })
}

๐Ÿ‘:-1

i solve it when subscribe the data i create new value let s = null and then i add data from subscribe into new value s and thatโ€™s working

chart():void{
  this.projectService.get_project(1).subscribe(data=>{
    let s=null
    s=data.visitor;
    console.log(data.visitor)
  console.log(this.visitor)
  const canvas = document.getElementById('myChart') as HTMLCanvasElement;
    const ctx = canvas.getContext('2d');
  var chart = new Chart(ctx, {
      // The type of chart we want to create
      type: 'line',
  
      // The data for our dataset
      data: {
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
          datasets: [{
              label: 'My First dataset',
              backgroundColor: 'rgb(255, 99, 132)',
              borderColor: 'rgb(255, 99, 132)',
              data: [s, 10, 5, 2, 20, 30, 45], 
              fill: true
          }]
      },
  
      // Configuration options go here
      options: {}
  });
})
}

Leave a comment