0
votes

[Kindly let me know how can I improve this question for your better understanding if I am not clear in describing the situation and what I want]

I am changing a chart in my angular app which we built earlier. We are using ng2-charts. Earlier we used TWO JSONs/Arrays. But the REST service (which I can't change as it is coming from a 3rd party service) is changed now. The new REST service looks like below. I tried with one JSON. I am able to see the graph when my input is a hard coded json in the .ts file itself.

But I am struggling when I am trying to get the JSON from a REST(GET) call.

FYI: I can see the JSON when I print it in the console. Please see the picture

I am getting error:

Cannot read property 'data' of undefined

Below are the two stackblitz examples. The first is with hard coded JSON and second one is from REST call:

https://stackblitz.com/edit/ng2-charts-line-template-iq1mia

https://stackblitz.com/edit/ng2-charts-line-template-voazjk

public summaryboardJson: Summaryboard[];
  public lineChartLegend = true;
  public lineChartType = 'line';
  public lineChartPlugins = [];
  public lineChartOptions: (ChartOptions & { annotation: any }) = {
    responsive: true,
  };
  public lineChartColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: 'rgba(255,0,0,0.3)',
    },
  ];
  public lineChartData: ChartDataSets[];
  public lineChartLabels: Label[];

 ngOnInit() {
        this.http
            .get("https://api.jsonbin.io/b/5c90f7d86892a7259f084846")
            .toPromise()
            .then(response => {
                const data = response.json();
                this.summaryboardJson = data;
                console.log(this.summaryboardJson);

              //START: put data in Bar Chart
              this.lineChartData = [
                { data: this.summaryboardJson.map(a => a.noOfDefects), label: 'Defects' },
              ];
              this.lineChartLabels = this.summaryboardJson.map(a => a.Month);
              //END: put data in Bar Chart

            })
            .catch(error => {
                console.log(error);
                return Observable.of<Summaryboard[]>([]);
            });

Any help on this, how to use the JSON from REST call to create the same chart?

enter image description here

1

1 Answers

0
votes

Try This:

https://stackblitz.com/edit/ng2-charts-line-template-umuhe1?file=src%2Fapp%2Fapp.component.ts

I have updated your second stackblitz

I initialized the lineChartLabels array to a new array and did an ngIf on the length.