0

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!

1 Answer 1

2

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();
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.