the data chart is malfunctioning

Is it possible to use a chart with Angular that dynamically retrieves data from an API? I am able to get the data from the API in ngOnInit, but encounter difficulties assigning it to the chart.

Below is the component TS code :

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { PageTitleService } from '../../core/page-title/page-title.service';
import { TranslateService } from '@ngx-translate/core';
import { StatistiqueService } from 'app/service/statistique/statistique.service';


@Component({
  selector: 'ms-charts',
  templateUrl:'./statstypedemande-component.html',
  styleUrls: ['./statstypedemande-component.scss'],
  encapsulation: ViewEncapsulation.None  
})

export class StatsTypeDemandeComponent implements OnInit {

   stats: number[];
   statistiques: [];

   constructor(private pageTitleService: PageTitleService,
               public translate: TranslateService,
               private serviceStatistique : StatistiqueService) {}

   ngOnInit() {
      this.translate.get('Statistique des types de demandes').subscribe((res: string) => {
        this.pageTitleService.setTitle(res);
      });

      this.serviceStatistique.getTest()
      .subscribe(res => {
         console.log(res);
         this.stats = res;
         console.log(this.stats);

      })      
   }

      // Doughnut
      public doughnutChartLabels = ['Entreprise', 'Salarié', 'Particulier'];
      public doughnutChartColors: any[] = [{ backgroundColor: ["#b8436d", "#00d9f9", "#a4c73c"] }];
      //public doughnutChartData:number[] = [350, 450, 100];
      public doughnutChartData:number[] = this.stats;
      public doughnutChartType:string = 'doughnut';

}

Now, let's look at the Service :

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class StatistiqueService {

  readonly rootURL = 'https://localhost:44319/api';
  list : number[];

  constructor(private http: HttpClient) { }

  getTest()
  {
      return this.http.get(this.rootURL + '/Demande/StatsTypeDemande');
  }
}

Last but not least, here is the Component HTML :

<!--Ng2 Charts-->
<div class="row">
    <!-- Doughnut Chart -->

    <div *ngFor="let a of stats">
        {{ a }}
    </div>   

    <div class="col-12 col-sm-6 col-md-6 col-lg-6">
        <div class="chk-block">
            <div class="chk-block-title">
                <div class="d-flex justify-content-between">
                    <div class="d-flex align-items-start flex-row">
                        <h3>Statistique des types de demande</h3>
                    </div>
                </div>
            </div>
            <div class="chk-block-content">
                <canvas baseChart height="100" [data]="doughnutChartData" [options]="PieChartOptions" [colors]="doughnutChartColors" [chartType]="doughnutChartType" [labels]="doughnutChartLabels"></canvas>
            </div>
        </div>
    </div>
</div>
<!-- Row Closed -->

Answer â„–1

Your template utilizes the doughnutChartData field to connect data from the component to the chart. Initially, you assign it to the this.stats field, which is empty at that point:

public doughnutChartData:number[] = this.stats;

Once the data is fetched from the API, you update the this.stats field:

this.serviceStatistique.getTest()
  .subscribe(res => {
    console.log(res);
    this.stats = res;
    console.log(this.stats);
  })

However, the doughnutChartData field (used in the template) still points to the undefined value of the previous this.stats.

You can either remove this.stats and directly set the data to the doughnutChartData field:

this.serviceStatistique.getTest()
  .subscribe(res => this.doughnutChartData = res)

Alternatively, remove doughnutChartData and modify the template to utilize the stats field instead:

<canvas baseChart
  height="100"
  [data]="stats"
  [options]="PieChartOptions"
  [colors]="doughnutChartColors"
  [chartType]="doughnutChartType"
  [labels]="doughnutChartLabels">
</canvas>

Check out this StackBlitz example for reference.

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

Combinations of Typescript dependent unions

I'm struggling with calling the given union that wraps a function and its argument. Is there a way to call it without having to cast? type Wrapper = { fn: (a: string) => void arg: string } | { fn: (a: number) => void arg: number } let f ...

Utilizing References in React Components

One of the challenges I am facing involves a Container that needs references to some of its child components: const Container = () => { const blocks: HTMLDivElement[] = []; return ( <div> <Navigation currentBlock={currentBlock} ...

Uninitialized Array Member in Angular 8

Can anyone explain why the code snippet below is printing "undefined"? I have created several objects and intended to display the corresponding images, but after iterating through them using ngfor, nothing appeared. To investigate, I logged the array and ...

Enhancing JavaScript functions with type definitions

I have successfully implemented this TypeScript code: import ytdl from 'react-native-ytdl'; type DirectLink = { url: string; headers: any[]; }; type VideoFormat = { itag: number; url: string; width: number; height: number; }; type ...

Angular unit testing - Accessing child components within an overlay container

I've created a unique custom component called MatSelectControls. Its implementation looks like this: <component-im-testing> <mat-select> <mat-select-controls></mat-select-controls> <mat-option *ngFor="..."> ...

Can NodeJs packages be incorporated into Angular projects?

Is it possible to use the Pluralize package in an Angular project? I'm encountering an error in VS Code that says 'Can't find module pluralize' when trying to import it. I am unsure if NodeJs packages can be used in Angular. Any help w ...

Tips for retrieving the angular route parameters from the URL?

I'm working with an Angular route that looks like this: /Chapter/:chapterId/Section/:sectionId. Let's say I have a URL such as: http://server.com/Chapter/1/Section/2?search=moby. Is there a way to extract the parameters and query string in Angu ...

Utilizing IonicSafeString for Alert Box Messages in Event Handling

.ts private async displayTermsOfServiceAlert(): Promise<void> { const alert = await this.alertController.create({ header: 'Updated Terms of Service', //problem lies here message: new IonicSafeString(`<ion-button i ...

mat-slider: experiencing delay in updating while dragging it

Incorporating @angular/material in my Angular 5 application has been quite the journey. The specific version of Angular Material that I have implemented is 5.0.2, along with @angular/animations 5.1.2. My usage of the slider component is rather straightfor ...

Issues arise when Typescript fails to convert an image URL into a base64 encoded string

My current challenge involves converting an image to base 64 format using its URL. This is the method I am currently using: convertToBase64(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.he ...

How come the hasOwnProperty function does not remove objects of type {}?

I am working with a complex type called ReactNode from the version @types/react 16.9.17 and TypeScript v3.7.4. import React, { ReactNode } from 'react'; My goal is to reduce this type to a new type that includes the property children. To achie ...

Creating a simple unit test for an angular "provider" functionality

I am currently in the process of setting up a basic unit test for my Angular application, specifically an Ionic application. Utilizing a preconfigured solution by the Ionic team with karma/jasmine, the provided sample unit tests passed successfully. Encour ...

Maintaining the ngFor value when clicked and passing it to another component

Currently tackling an angular project and seeking assistance with a particular issue... I have successfully displayed data from an array, but now I am looking to store the value of the element I click on so that I can utilize it in another component along ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

The function res.send() is returning a null object

I am facing an issue where the person object I am trying to send back using res.send() from the express backend to the angular frontend is always null. This data is being sent from the express backend at localhost/8081 to the angular frontend at localhost/ ...

Utilizing Angular 2 Service for Efficient Data Exchange Among Components

I'm experimenting with data sharing between components using a shared service. Here is the service: @Injectable() export class JobService { public jobType=null; public examples=[]; } My first component sets the jobType and examples variables ...

Guide on integrating TypeScript with the Esri Leaflet JavaScript Plugin

I'm working on an Aurelia project in TypeScript that incorporates Leaflet for mapping. So far, I've been able to use typings for Leaflet itself, but the esri-leaflet plugin is only available in JavaScript. How can I import and utilize this JavaSc ...

Using TypeScript and webpack, include the access_token in the http header when making requests with axios

I need to include an access_token in the header of axios, following this example: https://github.com/axios/axios#global-axios-defaults Currently, I am fetching the access_token using razor syntax, which is only accessible in CSHTML files. https://github ...

How to determine the champion in a game of tic tac toe with the help of Redux and React in

As a beginner in react and redux, I am currently self-studying the concepts. States in my tic-tac-toe project are managed using redux. My goal is to determine the winner when X or O are aligned on the board. Below is my code: // store.ts import { co ...

Accessing user information after logging in can be achieved through utilizing Web API in conjunction with Angular 5 Token Authentication

Every time I access my Angular app, the following information is displayed: access_token:"******************" expires_in:59 refresh_token:"******************" token_type:"bearer" However, I am now facing an issue where I cannot extract the user id from t ...