Estoy usando Chart.js en Angular. Cuando elijo una fecha en el calendario de una aplicación web, el servicio de descanso envía una respuesta, el gráfico se actualiza, los ejes x e y. En mi eje x tengo fechas como cadenas. Sin embargo, si mi respuesta tiene menos datos que antes (no todos los meses tienen la misma cantidad de días o no todas las respuestas tienen la misma cantidad de datos), el eje x no se reduce.
Este:
this.barChartLabels = this.xLabels; //an array with many elements if (selectedDateFormated === "2021-9-28") { this.barChartLabels = ["a","b","c","d"]; // overwrite for demo purpose }dará algo como esto:
Debe ser solo a,b,c,d en el eje x. ¿Como hacer eso?
Tengo esto en mi método subscribe() para eliminar datos anteriores, antes de actualizarlos nuevamente desde la API de descanso:
this.barChartLabels = []; this.barChartData[0].data = []; this.barChartData[1].data = []; this.xLabels = []; this.Consumption = []; this.Flow = []; this.chart.update(); this.resultSet.result.forEach(item => { this.xLabels.push( item.a ); this.Flow.push( +item.b //+ is casting string to number ); this.Consumption.push( +item.f ); }); this.barChartLabels = this.xLabels; this.barChartData[0].data = this.Consumption; this.barChartData[1].data = this.Flow; this.chart.chart.config.data.labels = this.xLabels;Esto de arriba hizo el truco. Y el gráfico es una referencia a un gráfico en una vista:
@ViewChild(BaseChartDirective, { static: true }) chart: BaseChartDirective; No sé qué hace realmente this.chart.chart.config y por qué. Se trata de un error en los gráficos ng2. Así que hice estos dos métodos y los llamé al final del método subscribe() cuando la respuesta de la API se inserta en mis matrices.
refresh_chart() { setTimeout(() => { console.log("xLabels: " + this.xLabels); console.log("Consumption: " + this.consumption); if (this.chart && this.chart.chart && this.chart.chart.config) { this.chart.chart.config.data.labels = this.xLabels; this.chart.chart.config.data.datasets[0].data = this.consumption; this.chart.chart.update(); } }); } clearCharts() { this.barChartLabels= []; this.emptyChartData(this.barChartData); } emptyChartData(obj) { obj[0].data = []; obj[1].data = []; }