angular - 如何将 API 数据放入角度图表?
问题描述
我正在尝试将 spotify API 放到图表中,这是我的图表组件:
来自Spotify的API:
ngOnInit() {
this.route.params.pipe(map((params) => params["id"])).subscribe((id) => {
this.userService.getAudioFeature(id).subscribe((trackFeature) => {
this.trackFeature = trackFeature;
console.log(this.trackFeature);
});
});
}
图表示例:
barChartOptions: ChartOptions = {
responsive: true,
};
barChartLabels: Label[] = [
"Apple",
"Banana",
"Kiwifruit",
"Blueberry",
"Orange",
"Grapes",
];
barChartType: ChartType = "bar";
barChartLegend = true;
barChartPlugins = [];
barChartData: ChartDataSets[] = [
{ data: [this.trackFeature.danceability, 37, 60, 70, 46, 33], label: "Audio Features" },
];
解决方案
你可以使用这个例子
数据必须采用以下格式...
public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
public barChartType: ChartType = 'bar';
public barChartLegend = true;
public barChartPlugins = [pluginDataLabels];
public barChartData: ChartDataSets[] = [
{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
{ data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' }
];
更新的答案:
export class AppComponent {
trackFeature:any;
public barChartOptions: ChartOptions = {
responsive: true,
};
public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
public barChartType: ChartType = 'bar';
public barChartLegend = true;
public barChartPlugins = [];
public barChartData: ChartDataSets[] = [
{ data: [10,20,30,40,50], label: 'Series A' }
];
constructor() {}
ngOnInit() {
//push data from api
this.route.params.pipe(map(params => params["id"])).subscribe(id => {
this.userService.getAudioFeature(id).subscribe(trackFeature => {
this.trackFeature = trackFeature;
//if data received then push into your chart
if (this.trackFeature != null) {
this.barChartData = [
{
data: [this.trackFeature.danceability, this.trackFeature.energy],
label: "Series A"
}
];
}
});
});
} //end ngOnInit
}
现场示例演示
我希望它对你有帮助。:)
推荐阅读
- apache-spark - 使用 union() 组合不同字段分区的历史数据和实时数据
- apache-spark - cassandra系统表中有没有办法检查计数?我们在哪里可以检查最新插入的元数据?
- apache-kafka - broker.id 在 kafka 中的重要性?
- fastreport - FastReport4 - 子带继承
- javascript - 通过 refs 响应访问 DOM 元素而不是对象
- dart - 颤振关闭条件内的对话框
- angular - 如何为原理图创建任务?
- javascript - getUserMedia() - 在移动设备上选择后置摄像头
- android - onBindViewHolder 乱七八糟图片
- ios - UITextView 光标拖动(长按放大镜)不起作用