i'm facing a challenge ploting ChartJs bar chart in my angular app with the data coming from my api response
this is the code snippets
<div class="canvas">
<canvas id="canvas" baseChart [data]="barChartData" [options]="barChartOptions" [plugins]="barChartPlugins"
[legend]="barChartLegend" [type]="'bar'">
</canvas>
</div>
this.barChartData = new Chart('canvas', {
type:"bar",
data: {
labels: ["Private", "NASHA", "NHIS", "Others"],
datasets:[{
data: [
this.apiResponse?.Private,
this.apiResponse?.data_1
],
label: 'hey',
backgroundColor: [ '#E8E2F4']
}]
},
options:{
scales: {
y:{
beginAtZero:true
}
}
}
})
now the issue is that the chart is not pupolating and when i console the api response befor creating the chart i get the values as expected, but when i console the value after the chart, it returns undefined
pls what can be the cause, and how do i fix it
As the
apiResponseis the response from the API, you should subscribe to the observable and assign the response value toapiResponse.My concern based on your current code is as you are using the NG2-Charts directive, you are not correctly passing the value to those inputs such as
[data],[options].Solution 1: With NG2-Charts
The
barChartDatashould be theChartData<'bar'>type but notChartConfiguration<'bar'>.Solution 2: Pure Chart.js
For pure Chart.js, you can do as below:
Demo @ StackBlitz