问题描述
如何动态地将数据分配给oughnutchartdata。如何通过ngOnIt上的subscription方法将来自服务文件的数据链接到oughnutchartdata。这样我就可以将多集数据链接到动态传入的数据而无需对其进行硬编码 我还可以通过链接到ctx.fillText
来动态显示中心数据我的.ts文件
public doughnutChartLabels: Label[] = ['Download Sales','In-Store Sales','Mail-Order Sales'];
public doughnutChartData: MultiDataSet = [
];
radius = length * Math.SQRT2 / 2;
colors= [
{
backgroundColor: [
'#E6B01C','#1454A3','#22C3BD','yellow'
]
}
];
public doughnutChartType: ChartType = 'doughnut';
public doughnutChartPlugins: PluginServiceGlobalRegistrationAndOptions[] = [{
beforeDraw(chart) {
const ctx = chart.ctx;
const txt = '26';
//Get options from the center object in options
const sidePadding = 60;
const sidePaddingCalculated = (sidePadding / 100) * (this.radius * 2)
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
const centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
//Get the width of the string and also the width of the element minus 10 to give it 5px side padding
const stringWidth = ctx.measureText(txt).width;
const elementWidth = (this.radius * 2) - sidePaddingCalculated;
// Find out how much the font can grow in width.
const widthRatio = elementWidth / stringWidth;
const newFontSize = Math.floor(30 * widthRatio);
const elementHeight = (this.radius * 2);
// Pick a new font size so it will not be larger than the height of label.
// const fontSizetoUse = Math.min(newFontSize,elementHeight);
// ctx.font = fontSizetoUse + 'px Arial';
ctx.fillStyle = 'blue';
// Draw text in center
ctx.fillText('26',centerX,centerY);
}
}];
constructor(private roleService:RoleDashboardService) { }
ngOnInit() {
this.roleService.getWidget).subscribe((data)=>{
console.log(data)
this.doughnutChartData
console.log(this.doughnutChartData)
})
}
// events
public chartClicked({ event,active }: { event: MouseEvent,active: {}[] }): void {
console.log(event,active);
}
public chartHovered({ event,active);
}
解决方法
取决于您使用的后端。例如,如果您通过mysql的php获取数据,则可以使用以下代码:
array1=[];
array2=[];
//api call on backend
this.http.get('http://localhost/angular9/chartData.php').subscribe(data => {
//create array and push the data
this.array1.push(data);
//assign this array to another arraya and map it
this.array2 = this.array1[0].map(function(item,keys) {
var mixarrayy = Object.keys(item).concat(Object.values(item));
return mixarrayy;
});