我正在尝试为我的单身汉的最终项目制作一个动态图表页面。首先,我有一个SQL度量标准数据库,它是通过这种方式检索的。
getmetrics(flag = 2) {
this.metricService.getmetrics()
.subscribe(res => {
this.metricService.metrics = res as metric[];
for (let metric of this.metricService.metrics) {
metric.canvas = "canvas" + metric.id_metric;
}
if (flag == 2) {
for (let i = 0; i < this.metricService.metrics.length; i++) {
//here we create the chart with createCharts(metric);
this.metricService.metrics[i] = this.createCharts(this.metricService.metrics[i]);
}
}
初始化视图后,将使用标记来创建图表,
ngOnInit() {
this.getmetrics(1);
}
ngAfterViewInit() {
this.getmetrics(2);
}
并且创建图表现在看起来是这样,以确保这只是前端中的问题。
createCharts(metric) {
metric.chart = new Chart(metric.canvas, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 24, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
return metric;
}
HTML看起来像这样:
<div class="col-6 metric" *ngFor="let metric of metricService.metrics">
<h5>{{metric.nombre}}</h5>
<div *ngIf = "metric.canvas">
<canvas id="{{metric.canvas}}">{{ metric.chart }}</canvas>
</div>
</div>
但是结果如下Picture of the result without the static chart它应该是这样的,但是每隔一张画布上都有第一个图表。Picture of the result with static chart另外,重要的是要说静态画布结果中的结果如下
<canvas _ngcontent-c2="" id="canvas0" width="450" height="225" class="chartjs-render-monitor" style="display: block; width: 450px; height: 225px;"></canvas>
并且动态(和目标)画布中的结果为
<canvas _ngcontent-c2="" id="canvas2"></canvas>
希望这会有所帮助,如果我在途中犯了一些错误,请对我的英语感到抱歉。
我做了些不同。我没有在*ngFor
内创建canvas标记,而是在组件代码处动态创建了图表canvas。
const wrapper = document.getElementById('chart-wrapper');
const newCanvas = document.createElement('canvas');
newCanvas.id = metric.canvas;
wrapper.appendChild(newCanvas);
const ctx = (newCanvas as HTMLCanvasElement).getContext('2d');
this.lineChart = new Chart(ctx, chartOptions);