我有一个简单的数据数组,我想使用chart.js库在图表中显示它。唯一的错误似乎是一些DeepPartialObject引用了图表选项中的一些问题(y轴和x轴)。我是Angular和Chart.js的新手,一直在努力解决这个问题。
我当前的代码如下所示:
import { Chart } from 'chart.js/auto';
import { Component, OnInit } from '@angular/core';
import { Fruit } from './fruit.model';
import { FruitService } from './fruit.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'angular-fetch-json-data';
public fruits: Fruit[];
public chart: any;
public constructor(private fruitService: FruitService) { }
public ngOnInit(): void {
this.fruitService.getFruits().subscribe((response) => {
this.fruits = response.fruits;
this.createChart();
})
}
createChart() {
if (this.chart) {
this.chart.destroy();
}
// Extract the labels and data from the fruits array
const labels = this.fruits.map((fruit: any) => fruit.fruit);
const data = this.fruits.map((fruit: any) => fruit.amountBought);
this.chart = new Chart('canvas', {
type: 'line',
data: {
labels: labels,
datasets: [
{
data: data,
borderColor: '#3cba9f',
fill: false
},
{
data: data,
borderColor: '#ffcc00',
fill: false
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true,
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
data.json file:
{
"fruits": [
{
"fruit": "Apple",
"size": "Large",
"color": "Red",
"amountBought": 100
},
{
"fruit": "Banana",
"size": "Small",
"color": "Yellow",
"amountBought": 76
},
{
"fruit": "Strawberry",
"size": "Medium",
"color": "Red",
"amountBought": 732
},
{
"fruit": "Blueberry",
"size": "Small",
"color": "Blue",
"amountBought": 27
}
]
}
The issues are with Yaxes and xAxes, at least according to the compiler. I've tried numerous things with those, and also changing different stuff with the chart options, but can't seem to figure it out.
2条答案
按热度按时间qeeaahzv1#
问题1
正如@Stefan提到的,由于可观察对象是异步的,因此在
subscribe()
回调中移动this.createChart()
。通过移动到回调中,将保证this.createChart()
在返回可观察对象时执行。问题2
我认为您安装的 chart.js 版本为3或更高版本,这与您当前的Chart.js配置不兼容。根据文档,不再支持xAxes和yAxes。请按照迁移说明进行操作:
xAxes
和yAxes
阵列,轴选项现在是按比例ID键控的单独比例legend
、title
和tooltip
命名空间已从options
移动到options.plugins
要从组件呈现图表(回写代码),您应该使用
@ViewChild
装饰器。您的代码应该如下所示:
组件
超文本标记语言
Demo @ StackBlitz
rryofs0p2#
在你们的帮助下我完成了代码!非常感谢!下面是工作代码: