The Angular chart is not displaying any data retrieved from the API response

I am currently experiencing a problem with plotting a ChartJs bar chart in my Angular application using data retrieved from an API response.

Below is the code snippet:

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

The issue lies in the fact that the chart is not populating. When I console log the API response before creating the chart, the values are as expected. However, after creating the chart, the values return undefined.

What could be causing this issue and how can I resolve it?

Answer №1

When dealing with the response from the API, it is important to subscribe to the observable and assign the value to the variable apiResponse.

The issue in your current code lies in correctly passing values to inputs like [data] and [options] when using the NG2-Charts directive.

Recommendation 1: Using NG2-Charts

The type of barChartData should be ChartData<'bar'> instead of ChartConfiguration<'bar'>.

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

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

of({
  Private: 6,
  data_1: 15,
}) /* Update this with your API call observable */
  .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'],
        },
      ],
    };
  });

Recommendation 2: Using Pure Chart.js

If you prefer working with Pure Chart.js, follow this example:

of({
  Private: 6,
  data_1: 15,
}) /* Update this with your API call observable */
  .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'>);
  });

Check out the demo on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Three pie or doughnut charts instead of one are utilized within Chart.js

Can multiple charts be nested inside one another? To see an example of a single chart and what I would like - where the first one is placed inside the second one and so on - please refer to this js fiddle. var data = [ { label: "title 1", value: ...

Mat-paginator in Angular does not show up in mat-table

While working with Angular 12, I have imported the mat-paginator component using the following code: import { MatPaginator } from '@angular/material/paginator'; Then, in the export section, I attempted to reference the paginator with both of the ...

"Encountering a problem with the debounceTime operator in rxjs and HTTP requests while using the keyup

I have been working on implementing server-side search in Angular 7. I managed to find some code for implementation, but unfortunately it is not functioning as expected. The issue I am encountering is that when searching for a string, the code sends mult ...

What are the advantages of combining the website URL and API URL within the Angular service?

When deploying my application in a production environment, I encounter an issue with the URL addresses. The web address is , while the API address is . However, when making a request to the API through Angular, the URLs get concatenated into . This issue d ...

Tips for configuring VSCode to display strictNullChecks Typescript errors

Whenever I compile my project using the specified tsconfig.json settings, an error occurs after enabling strictNullChecks: true. { "version": "2.3.4", "compilerOptions": { "allowSyntheticDefaultImports": false, "removeComments": tr ...

Guide to Setting Up "Remember Me" Login for Users in Angular

I am having trouble setting the 'Remember Me' option on my Login page. I tried using localstorage session but it seems like something is missing in the service file that's causing it not to respond properly. I attempted to follow a guide on ...

Angular - Utilizing nested arrays for efficient file uploading

I am currently working on building a file uploader using Angular. My goal is to be able to upload different types of files, with each button capable of uploading multiple files at once. However, I am running into an issue where the uploaded files are not b ...

"Maximizing the potential of Bootstrap and Ionic within Angular: A step-by

I have an Angular project created using the Ionic framework, but I also want to incorporate Bootstrap. How can I achieve this? I have installed Bootstrap and made changes to the angular.json file as shown below: "styles": [ { ...

Recursive rendering of tree components in React

I am facing a challenge in rendering tree items recursively using React. I have been struggling to achieve the desired outcome as calling treeRender(children) seems to alter the data structure when a folder is encountered for the first time. I am curious a ...

I'm curious as to why my array is only being filled within the subscription function

When I call the GetAllMainStore() function, data is successfully retrieved from the API and the console indicates that "this.MainStoreArray" contains data. The problem arises when I attempt to access "this.MainStoreArray" outside of the GetAllMainStore() ...

Navigating focus within form elements using Angular techniques

Purpose There is a form with various input elements (el1, el2 ...) el1 may or may not have initial focus when a keydown event occurs, the following actions should be taken: If none of the input elements are in focus, move focus to the first non-empty e ...

Can you explain the concept of interface with dual function type declarations and provide guidance on its implementation?

interface MyInterface { (choose: string): number; (item: number): string; } Can you provide guidance on using the MyInterface interface mentioned above? How would it be helpful in practical situations? ...

String interpolation can be used to easily accept numbers with dot separators

Is it possible to create a function that can accept numbers with dot separators? Here are some examples: func('100.000.002.333') // should pass func('10') // should pass func('20') // should pass func('100') // shou ...

Unable to locate element within the HTML code in Angular

Despite using document.getElementByID, I am unable to retrieve the value of the list element in the HTML. The code shows that the element is undefined, even though it has the same id. Here is the snippet of code: fileupload.component.ts: ngOnInit() { ...

Transforming button click from EventEmitter to RXJS observable

This is the functionality of the component utilizing EventEmitter: import { Component, Output, EventEmitter } from "@angular/core"; @Component({ selector: "app-my-component", template: ` <button (click)="clickEvent($event)& ...

Issue: Module '@ngtools/json-schema' not found on Mac operating system

After installing angular-cli on my Mac using the command: brew install angular-cli I encountered an error when trying to run ng g service test: module.js:538 throw err; ^ Error: Cannot find module '@ngtools/json-schema' at Functio ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Is there a way to make Typescript accept dot notation?

Is there a way to suppress the compile time error in Typescript when using dot notation to access a property that the compiler doesn't know about? Even though using bracket notation works, dot notation would be much more readable in my specific case. ...

Testing the HttpInterceptor functionality in Angular 4 through unit tests

I'm looking for guidance on testing the HttpInterceptor functionality provided by Angular 4. I've created an interceptor based on examples, but I'm unsure about how to properly test it. Below is my interceptor code, and I aim to verify that ...

Trouble installing TypeScript on MacBook - Terminal Glitch

I recently got Visual Studio Code on my Mac and wanted to add TypeScript for Angular. I believe I already installed Node.js or Git in the past. However, when I tried running this command from the TypeScript website in the Mac Terminal to install TypeScript ...