如何使用 API 获取数据来初始化图表?
how to initialize chart with API fetch data?
我想为我的项目使用 ngx-charts
。问题是我不明白如何使用从 api.
获得的数据来初始化我的图表
垂直条形图看起来很简单。数据属于以下类型:
https://stackblitz.com/edit/vertical-bar-chart?embed=1&file=app/app.component.ts
当我在 constructor
Object.assign(this, data)
(我从 api 得到的 data
)中赋值时,我收到以下错误:
ERROR TypeError: Cannot read property 'toLocaleString' of undefined
他们的数据是以下类型:
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[];
ngOnInit() {
this.shipService.getConsumuriSiDataForShipById(this.shipId).subscribe(data
=> {
console.log(data);
this.single = data;
});
并且在您的组件中,您必须 map
将数据转换为 ngx-charts 可以理解的格式。在这里,试一试:
...
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 }));
});
}
...
}
Here's a Working Sample StackBlitz for your ref.
我想为我的项目使用 ngx-charts
。问题是我不明白如何使用从 api.
垂直条形图看起来很简单。数据属于以下类型:
https://stackblitz.com/edit/vertical-bar-chart?embed=1&file=app/app.component.ts
当我在 constructor
Object.assign(this, data)
(我从 api 得到的 data
)中赋值时,我收到以下错误:
ERROR TypeError: Cannot read property 'toLocaleString' of undefined
他们的数据是以下类型:
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[];
ngOnInit() {
this.shipService.getConsumuriSiDataForShipById(this.shipId).subscribe(data
=> {
console.log(data);
this.single = data;
});
并且在您的组件中,您必须 map
将数据转换为 ngx-charts 可以理解的格式。在这里,试一试:
...
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 }));
});
}
...
}
Here's a Working Sample StackBlitz for your ref.