Reputation: 338
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).
Upvotes: 2
Views: 871
Reputation: 368
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',
}
];
});
Upvotes: 4