Chartjs-Consuming an API and displaying items in chart/Angular

1👍

What I can see from your code, you’re creating a chart outside of the subscribe which means, you create it when don’t have any data yet. You should move that creation inside the subscribe.

Something like this:

ngOnInit() {
    this.wrService.getWritersList().subscribe(
        res => {
            this.wrs=res;
            this.nms=res.username;
            this.bks=res.nb_published_books;
            console.log(res);

            // Line chart:
            this.LineChart = new Chart('lineChart', {
                type: 'line',
                data: {

                    labels: this.nms,
                    datasets: [{
                        label: 'Number of published books',

                        data: this.bks,
                        fill:false,
                        lineTension:0.2,
                        borderColor:"red",
                        borderWidth: 1
                    }]
                }, 
                options: {
                    title:{
                        text:"Line Chart",
                        display:true
                    },
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero:true
                            }
                        }]
                    }
                }
            }
        });
}

0👍

Try changing

getWritersList(): Observable<any> {
    return this.http.get<Writer[]>('http://localhost:8088/users/getall');
  }

to

getWritersList(): Observable<any> {
    return this.http.get<any>('http://localhost:8088/users/getall');
  }

and see if it helps.

Leave a comment