如何使用API来初始化图表以获取数据? [英] how to initialize chart with API fetch data?
问题描述
我想在我的项目中使用 ngx-charts
.问题是我不明白如何使用从api中获得的数据来初始化图表.
I want to use ngx-charts
for my project. The problem is I don't understand how to initialize my chart with data I got from my api.
垂直条形图似乎很容易.数据具有以下类型:
The vertical bar chart seems easy. The data is of the following type:
https://stackblitz.com/edit/vertical-bar-chart?embed = 1& file = app/app.component.ts
当我在构造函数
Object.assign(this,data)
(从我的api获得的 data
)中进行分配时,我收到了以下错误:
When I assign in the constructor
Object.assign(this, data)
(the data
I got from my api)) I receive the following error :
错误TypeError:无法读取未定义的属性'toLocaleString'
ERROR TypeError: Cannot read property 'toLocaleString' of undefined
他们的数据是以下类型:
Their data is the following type:
export var single = [{
"name": "Germany",
"value": 8940000
},
{
"name": "USA",
"value": 5000000
},
{
"name": "France",
"value": 7200000
}
];
我的数据是:
[{
"data": "2019-01-09",
"totalConsum24": 66.66666666666667
},
{
"data": "2019-02-03",
"totalConsum24": 160
},
{
"data": "2019-02-04",
"totalConsum24": 153.84615384615384
},
{
"data": "2019-02-05",
"totalConsum24": 90.9090909090909
}
]
Edit1:这是我从后端获取数据的方式.数据与我上面发布的相同.在COnstructor中,我从Object.assign(this,{single})开始,最初是单身:any [];
This is how i get my data from my backend. the data is the same as i posted above. In the COnstructor I begin with Object.assign(this, {single}) and initially single: any[];
ngOnInit() {
this.shipService.getConsumuriSiDataForShipById(this.shipId).subscribe(data
=> {
console.log(data);
this.single = data;
});
推荐答案
在组件中,您必须将数据映射
到ngx-charts可以理解的格式.在这里,尝试一下:
And in your Component, you'll have to map
the data to the format that the ngx-charts understand. Here, give this a try:
...
import { ShipService } from './path-to-ship-service';
@Component({...})
export class AppComponent {
...,
single = [];
constructor(private shipService: ShipService) {}
ngOnInit() {
this.shipService.getConsumuriSiDataForShipById(this.shipId)
.subscribe(data => {
console.log(data);
this.single = data.map(datum => ({ name: datum.data, value: datum.totalConsum24 }));
});
}
...
}
这是一个 正在处理示例StackBlitz 供您参考.
这篇关于如何使用API来初始化图表以获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!