0

I am trying to get a graph to display my data using ng2-charts. Everything works fine using mock-up data, however when I try to iterate over an Array passed by my parent component the graph itself doesn't display, only the orthogonal mark and nothing appears in the console. I've narrowed down the problem to the labels array : if you remove the commented line in the LineChartComponent it works.

Here is my code :

import { Component, Input } from '@angular/core';
import { CHART_DIRECTIVES } from 'ng2-charts/ng2-charts';
import { Traffic } from './traffic';

@Component({
  selector: 'line-chart-component',
  directives: [CHART_DIRECTIVES],
  styles: [`
    .chart {
      display: block;
    }
  `],
  template: `
  <div style="display: block">
        <canvas baseChart
              [datasets]="datasets"
              [labels]="labels"
              [chartType]="'line'"
              (chartHover)="chartHovered($event)"
              (chartClick)="chartClicked($event)"></canvas>
        </div>
  `
})

export class LineChartComponent {
  _dataArray: Traffic[] = [];    
  private datasets = [
      {
        label: "Desktop",
        data: []
      }
    ];    
  private labels: string [] = [];

  @Input()
  set dataArray(dataArray: Traffic[]) {
    dataArray.forEach((data: any,index: number) => {
      this.datasets[0].data.push(Math.round(data.Value));
      this.labels.push(data.Date));
    });
    // this.labels = ['0','1','2','3','4','5','6','7','8','9','10','11'];
  }

  get dataArray() { return this._dataArray; }

  private options = {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  };
}

N.B : None of the arrays are undefined. And both have a good structure, contain all my data and have an appropriate typing. Also, Data.date returns a String.

What could lead to such a behaviour ?

Thanks !

1 Answers1

0

So here is the answer : It appears that there is some kind of race condition between the two arrays. My guess is that the push of labels takes longer than the push of numbers, and therefore the graph doesn't load properly. Calling this.datasets = this.datasets.slice(); at the end of my setter to update the graph did the trick.