2

I am trying to show the data from the bgpie API in my chart. The data property of the chart accepts this format:

chartOptions: Options = {
   
  ...

  series: [{
            ...
            data: [[1, 5], [2, 3], [3, 8]];
            ...
          }]

The format is an array of couples with the first value of the couple being the x-axis value and the second being the y-axis value. My API has a different format: [{item1,item2}, {item1,item2}, {item1,item2}].

In order to change it to [[item1,item2], [item1,item2], [item1,item2]] I've done this:

chartDataX: number[] = [];
chartDataY: number[] = [];
chartData: any[] = [];


ngOnInit(): void {
    this.chartService.getMostFrequentUpdateData().subscribe(
      (data: ChartData[]) => {
        for (let i = 0; i < data.length; i++){
          this.chartDataX.push(data[i].item1);
          this.chartDataY.push(data[i].item2);
          this.chartData.push([this.chartDataX[i], this.chartDataY[i]]);
        }
      });
    this.chartOptions.series = [
          {
            name: 'ao',
            type: 'line',
            data: this.chartData,
            color: '#009879',
          }
        ];

}

With getMostFrequentUpdateData() being a function that makes the http call to the API:

getMostFrequentUpdateData(): Observable<ChartData[]>{
    return this.http.get<ChartData[]>('https://bgpie.net/api/rrc/00/mostfrequentstatefrequencycdf');
  }

This is a public repository containing the project (There might be some merge conflicts).

2
  • 1
    @OlegValter Noted, thank you Commented May 2, 2021 at 20:22
  • 2
    Would be much easier to help you if you could resolve the merge conflicts in that code if it is yours or provide us with a working code. Commented May 3, 2021 at 5:48

1 Answer 1

4

The susbcribe is async so your this.chartData is empty when you are assigning it to the chart object.

You can refactor as below with some suggestions to improve the code as well:

this.chartService.getMostFrequentUpdateData().subscribe(
      (data: ChartData[]) => {
        this.chartOptions.series = [
          {
            name: 'ao',
            type: 'line',
            data: data.map(e => [e.item1, e.item2]),
            color: '#009879',
          }
        ]; 
      });
Sign up to request clarification or add additional context in comments.

1 Comment

Editor's note: please don't include chit-chat in answers, thank you. Re: comment editing - you can only edit them for 5 minutes + it is discouraged to give answers in comments (if you can provide an answer, of course). Other than that - all good!

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.