2

I am fetching json data in the form:

[2193,3635,8417,0]

from localhost:8080. I want this dataset to act as canvas data in the form of pie chart.

Here is one.html code:

<div>
  <canvas
      baseChart
      [chartType]="'pie'"
      [datasets]="pieChartData"
      [labels]="pieChartLabels"
      [options]="pieChartOptions"
      [legend]="true"
      [colors]="pieChartColor"
      (chartClick)="onChartClick($event)">
  </canvas>
</div>

Here is one.ts code:

constructor(private router: Router, private userService: UserService,private http: HttpClient) { }

      pieChartOptions = {
        responsive: true
    }

    pieChartLabels =  ['PENDING', 'SUCCESS', 'FAIL', 'CREATED'];

    // CHART COLOR.
    pieChartColor:any = [
        {
            backgroundColor: ['rgba(30, 169, 224, 0.8)',
            'rgba(255,165,0,0.9)',
            'rgba(139, 136, 136, 0.9)',
            'rgba(255, 161, 181, 0.9)',
            ]
        }
    ]

    pieChartData:any = [
        { 
            data: []
        }
    ];

  ngOnInit() {

      this.http.get('http://localhost:8080/Graph', {responseType: 'json'}).subscribe(
        data => {
            this.pieChartData = data as any [];  // FILL THE CHART ARRAY WITH DATA.
        },
        (err: HttpErrorResponse) => {
            console.log (err.message);
        }
    );
  }


  onChartClick(event: any) {
    console.log(event);
}

But while running the code, I am not able to see the pie chart, with labels strikedthrough and getting this console error:

ListUserComponent.html:25 ERROR TypeError: Cannot read property 'length' of undefined
    at ng2-charts.js:382
    at Array.filter (<anonymous>)
    at BaseChartDirective.push../node_modules/ng2-charts/fesm5/ng2-charts.js.BaseChartDirective.ngDoCheck (ng2-charts.js:377)
    at checkAndUpdateDirectiveInline (core.js:10100)
    at checkAndUpdateNodeInline (core.js:11363)
    at checkAndUpdateNode (core.js:11325)
    at debugCheckAndUpdateNode (core.js:11962)
    at debugCheckDirectivesFn (core.js:11922)
    at Object.eval [as updateDirectives] (ListUserComponent.html:25)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11914)

Is there any mistake in the code? I am not sure of pieChartData properly taking the json object, or is there any other way to fetch json data?

Please, can I get a help?

Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
Sophia
  • 145
  • 2
  • 12

1 Answers1

1

when i tried to replicate your code, i got the same issue that legends had a strike through them... the reason was the format of the pieChartData:any object and the data [2193,3635,8417,0] which was being fed into it!!

You had defined pieChartData as an array with single object with a data property which consisted of an array.

pieChartData:any = [ { data: [] } ];

While, the values were being set as a number array [2193,3635,8417,0], which means:

pieChartData:any = [];

To replicate the delay caused by your HTTP call...i used setTimeout and got the form working as intended...

relevant TS:

import { Component } from '@angular/core';
import { ChartType, ChartOptions } from 'chart.js';
import { Label } from 'ng2-charts';
import * as pluginDataLabels from 'chartjs-plugin-datalabels';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  someData: any[] = [];

  public pieChartOptions: ChartOptions = {
    responsive: true,
    legend: {
      position: 'top',
    },
    plugins: {
      datalabels: {
        formatter: (value, ctx) => {
          const label = ctx.chart.data.labels[ctx.dataIndex];
          return label;
        },
      },
    }
  };
  public pieChartLabels: Label[] = ['PENDING', 'SUCCESS', 'FAIL', 'CREATED'];
  public pieChartType: ChartType = 'pie';
  public pieChartLegend = true;
  public pieChartPlugins = [pluginDataLabels];
  public pieChartColors = [
    {
      backgroundColor: ['rgba(30, 169, 224, 0.8)',
        'rgba(255,165,0,0.9)',
        'rgba(139, 136, 136, 0.9)',
        'rgba(255, 161, 181, 0.9)',
      ]
    },
  ];
  //public pieChartData: number[] = [2193,3635,8417,0];
  public pieChartData: number[] = [];

  constructor() { }

  ngOnInit() {
    setTimeout(() => {
      this.someData = [300, 500, 100];
      this.pieChartData = this.someData;
    }, 5000);
  }

}

relevant HTML:

<hello name="{{ name }}"></hello>

<div *ngIf='this.someData.length <=0'>
  Please wait while the latest data is fetched
</div>

<div *ngIf='this.someData.length >0'>
  We got data: {{this.someData.length}}

<div class="chart">
      <canvas baseChart
        [data]="pieChartData"
        [labels]="pieChartLabels"
        [chartType]="pieChartType"
        [options]="pieChartOptions"
        [plugins]="pieChartPlugins"
        [colors]="pieChartColors"
        [legend]="pieChartLegend">
      </canvas>
    </div>
</div>

working stackblitz available here

Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70