我有角度更新图表js的问题。我正在使用它的ngrx商店。
在选择器订户中(在ngOnInit中运行),我尝试更新图表数据:
this.yrSubscription = this.userDataStore.pipe(select(selectYrReport))
.subscribe(el => {
el.sessions.forEach(item => {
this.datasetsSessions[0].data.push(+item);
});
});
以及我的图表数据:
datasetsSessions: ChartDataSets[] = [{
label: 'Sessions',
data: [],
fill: false
}];
注册图表:
private _registerCustomChartJSPlugin(): void {
(window as any).Chart.plugins.register({
afterDatasetsDraw: (chart, easing): any => {
if (!chart.options.plugins.xLabelsOnTop
|| (chart.options.plugins.xLabelsOnTop && chart.options.plugins.xLabelsOnTop.active === false)) {
return;
}
const ctx = chart.ctx;
chart.data.datasets.forEach((dataset, i): any => {
const meta = chart.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach((element, index): any => {
// Draw the text in black, with the specified font
ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
const fontSize = 13;
const fontStyle = 'normal';
const fontFamily = 'Roboto, Helvetica Neue, Arial';
ctx.font = (window as any).Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
const dataString = dataset.data[index].toString() + 'k';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const padding = 15;
const startY = 24;
const position = element.tooltipPosition();
ctx.fillText(dataString, position.x, startY);
ctx.save();
ctx.beginPath();
ctx.setLineDash([5, 3]);
ctx.moveTo(position.x, startY + padding);
ctx.lineTo(position.x, position.y - padding);
ctx.strokeStyle = 'rgba(255,255,255,0.12)';
ctx.stroke();
ctx.restore();
});
}
});
}
});
}
而且我在构造函数中称呼它。
我知道,我需要运行chart.update()。但是仍然有关于图表未定义等的错误。
您没有通过上下文。例如:工作Stackblitz:-https://stackblitz.com/edit/angular-82ph1e
HTML:-
<div>
<canvas id="canvas">{{ chart }}</canvas>
</div>
CSS:-
canvas {
width: 100px;
height: 100px;
}
TS:-
import { Component, OnInit, AfterViewInit } from '@angular/core';
var require: any;
var Chart = require('chart.js');
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
chart;
ngOnInit() {
this.chart = new Chart('canvas', {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 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
}
}]
}
}
});
this.chart.update();
}
}