up94up
up94up

Reputation: 15

angular 4 line chart data is not showing data from http get

I am trying to create line chart using Angular 4 and chart.js using data from database provided by http get method. Situation is weird:

export class ValvesComponent implements OnInit {
  valves: Valve[];
  ignitions: number[] = [8, 5, 8, 9, 5, 3];
  dates: Date[];
  selectedValve: Valve;
  lineChartData: Array<any>;

  constructor(private dataService: DataService) {
    this.dataService.getIgnitions().then(ignitions => this.ignitions = ignitions);
    this.lineChartData = [{data: this.ignitions, label: 'Series Z'}];
  }

I declare array ignitions: number[] with random values. Then in constructor I am setting new values to this line chart data but it is not working. When I list all of ignitions values in html file everything works OK, data are the same as my get method returns. But chart shows still the old ones. Here is how i get those data:

    getIgnitions(): Promise<number[]> {
    return this.http.get(this.ignitionsUrl)
  .toPromise()
  .then(response => response.json() as number[])
  .catch(this.handleError);

}

and at the end Java method from controller.

    @GetMapping("/valve/findallignitions")
public Integer [] findAllIgnitions() {
    Iterable<Valve> valvess = valveRepository.findAll();
    List<Integer> valves = new ArrayList<>();
    Integer [] valvesArray = {1};
    for (Valve v : valvess) {
        valvesArray =  addElement(valvesArray, v.getIgnition());
    }
    return valvesArray;
}

What should I do to make it work ok, to get data frm http get in my line chart?

Thanks in advance for help!

Upvotes: 0

Views: 691

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222720

This is a common issue with ng2-charts , you will have call a redraw method so ng2-charts know to update the chart.Because it isn't watching for data changes, you have to manually tell it to update.

Inside your component

@ViewChild(BaseChartDirective) private _chart;

refer and refresh the chart as follows,

 forceChartRefresh() {
      setTimeout(() => {
        this._chart.refresh();
      }, 10);
    }


constructor(private dataService: DataService) {
    this.dataService.getIgnitions().then(ignitions => this.ignitions = ignitions);
    this.lineChartData = [{data: this.ignitions, label: 'Series Z'}];
    this.forceChartRefresh();
  }

Upvotes: 2

Related Questions