Angular chart not populating with data from API response

0๐Ÿ‘

โœ…

As the apiResponse is the response from the API, you should subscribe to the observable and assign the response value to apiResponse.

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 barChartData should be the ChartData<'bar'> type but not ChartConfiguration<'bar'>.

barChartData!: ChartData<'bar'>;
barChartOptions!: ChartOptions<'bar'>;
barChartPlugins!: any;
barChartLegend = true;

this.barChartOptions = {
  scales: {
    y: {
      beginAtZero: true,
    },
  },
};

of({
  Private: 6,
  data_1: 15,
}) /* Replace this with the observable that you call the API */
  .subscribe((resp) => {
    this.apiResponse = resp;

    this.barChartData = {
      labels: ['Private', 'NASHA', 'NHIS', 'Others'],
      datasets: [
        {
          data: [this.apiResponse?.Private, this.apiResponse?.data_1],
          label: 'hey',
          backgroundColor: ['#E8E2F4'],
        },
      ],
    };
  });

Solution 2: Pure Chart.js

For pure Chart.js, you can do as below:

of({
  Private: 6,
  data_1: 15,
}) /* Replace this with the observable that you call the API */
  .subscribe((resp) => {
    this.apiResponse = resp;

    new Chart('canvas2', {
      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,
          },
        },
      },
    } as ChartConfiguration<'bar'>);
  });

Demo @ StackBlitz

Leave a comment