My goal is to populate the data property of my chart with values obtained from an external API: .
I've defined an Interface that matches the structure of the data:
export interface ChartData{
item1: number;
item2: number;
}
This snippet represents how my chart looks like:
chartOptions: Options = {
title: {
text: 'CDF of the most frequent update frequency',
style: {
color: 'whitesmoke'
}
},
chart: {
type: 'line',
zoomType: 'x',
backgroundColor: '#323232',
},
...
series: [],
...
};
I am now attempting to assign the retrieved data (from the API) to the data property inside the series. Here's a hardcoded example:
series: [
{
data: [[1, 2], [2, 4], [3, 7] ...]
The first value in each pair corresponds to the x-axis, and the second value relates to the y-axis. The ChartData Interface also follows this pattern: item1 represents the x-axis value, and item2 represents the y-axis value. Below is my implementation:
ngOnInit(): void {
this.chartService.getMostFrequentUpdateData().subscribe(
(data: ChartData[]) => {
this.chartOptions.series = [
{
name: 'ao',
type: 'line',
data: data,
color: '#009879',
}
];
});
}
An error is encountered stating Type 'ChartData[]' is not assignable to type '(number | PointOptionsObject | [string | number, number | null] | null)[]'. I realize ChartData should actually be an ARRAY containing two numbers instead of just two numbers which seems to be causing the issue.
For further clarification, here's the http call within my service:
getMostFrequentUpdateData(): Observable<ChartData[]>{
return this.http.get<ChartData[]>('https://bgpie.net/api/rrc/00/mostfrequentstatefrequencycdf');
}
You can access the project on GitHub: https://github.com/mauri5566/sitocopy/blob/master/src/app/components/home/modal-most-frequent-update/modal-most-frequent-update.component.ts. Please note there might be merge conflicts present.
EDIT:
Despite making adjustments based on suggestions, the data still remains invisible on the chart. Using console.log confirms that chartData
holds the following values:
0: (2) [0, 0]
1: (2) [1, 98.60093378412567]
2: (2) [2, 99.69295521976126]
3: (2) [3, 99.79668345638125]
...
The way these values are structured appears accurate as they form pairs. The structure of the ChartData Interface has not changed. Below is how I handle ngOnInit
:
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',
}
];
}