我使用 Angular 开发环境 7 我正在尝试运行 ng2 谷歌图表的饼图 通过 API - 和 Angular 服务。
附件是我的TS文件的图片
问题:如何将来自数组的值输入到图表的数据表中?
谢谢
constructor(private _getIncomeService: getIncomeService) { }
_GetAveragesModel: GetAveragesModel[];
ngOnInit() {
this.fnGetAverages();
}
fnGetAverages() {
this._getIncomeService.GetAverages(279).subscribe(x => {
this._GetAveragesModel = x;
});
}
public pieChart = {
chartType: 'PieChart',
dataTable: [
['Task', 'Hours per Day'],
['ss', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
],
options: {
title: 'Tasks',
slices: {
0: { offset: 0.3 },
1: { offset: 0.2 },
},
width: '100%', height: '100%',
is3D: true,
chartArea: {left: "3%",top: "3%",height: "94%",width: "94%"}
}
};
```[enter image description here][1]
[1]: /image/1RMwk.png
最佳答案
不要使用 ng2-google-chart,而是使用 angular-google-charts(npm i angular-google-charts)。
这是 HTML 代码 您有一个类似 [data] 的标签和值“dataichange” => 您可以更改 ts 文件中的名称
<google-chart #chart
[title]="title"
[type]="type"
[data]="dataichange"
[columnNames]="columnNames"
[options]="options"
[width]="width"
[height]="height">
</google-chart>
这是带有硬编码数据的 .ts 文件
title = 'Browser market shares at a specific website, 2014';
type = 'PieChart';
dataichange = [
['Firefox', 45.0],
['IE', 26.8],
['Chrome', 12.8],
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
];
columnNames = ['Browser', 'Percentage'];
options = {
};
width = 550;
height = 400;
要解决您的问题 - 将数据替换为您自己的新数组。
您需要一个新数组,因为来自服务的数组太大。
因此,您需要为特定图表所需的列创建一个新数组。
为此,我使用“map”获取数组列,然后“push”按照我设置的顺序在新数组中创建它们。
Datachart: any[];
fnGetAverages() {
this._getIncomeService.GetAverages(279).subscribe(Res => {
this._GetAveragesModel = Res;
Res.map(item => {
this.Datachart.push([item.OrderTypeName, item.AveragePerDiner]);
})
});
}
现在替换 HTML 中的 [data]="Datachart" DataChart 是您过滤后的新数组
<google-chart #chart
[title]="title"
[type]="type"
[data]="Datachart" // Here I changed to the new array name "Datachart"
[columnNames]="columnNames"
[options]="options"
[width]="width"
[height]="height">
</google-chart>
关于angular - 如何将数组数据插入到 Angular 7中的ng2-google-chart图表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56022333/