在条形图中获取空数据

时间:2019-03-15 14:45:39

标签: angular angular-material angular6 bar-chart

我正在使用BarChart并通过api获取值。当我从后端获取数据并在BarChart中显示为空时。

以下是我的HTML代码

<div fxFlex.gt-sm="33.33%" fxFlex.gt-xs="50" fxFlex="100">
    <mat-card>
      <mat-card-content>
        <canvas height="200" baseChart class="chart" [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions"
          [colors]="chartColors" [legend]="barChartLegend" [chartType]="barChartType"></canvas>
      </mat-card-content>
    </mat-card>
  </div>

打字稿:

// Bar
  barChartLabels: string[] = ['0-20', '21-40', '41-60', '61-80', '81-100'];
  barChartType = 'bar';
  barChartLegend = true;
  barChartData: any[] = [{
    data: []
  }];
  barChartOptions: any = Object.assign({
    scaleShowVerticalLines: false,
    tooltips: {
      mode: 'index',
      intersect: false
    },
    responsive: true,
    scales: {
      xAxes: [{
        gridLines: {
          color: 'rgba(0,0,0,0.02)',
          defaultFontColor: 'rgba(0,0,0,0.02)',
          zeroLineColor: 'rgba(0,0,0,0.02)'
        },
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }],
      yAxes: [{
        gridLines: {
          color: 'rgba(0,0,0,0.02)',
          defaultFontColor: 'rgba(0,0,0,0.02)',
          zeroLineColor: 'rgba(0,0,0,0.02)'
        },
        stacked: true
      }]
    }
  }, this.globalChartOptions);

我正在调用api

this.patientService.agecount().subscribe(res => {
            const agetest = JSON.stringify(res);
         console.log('agetesting' + agetest);
         this.agechart.push(res);
         console.log('testing' + this.agechart);
         this.agetest1();
        });

    agetest1() {
      this.databar = this.agechart;
      console.log('testing the data' + JSON.stringify(this.databar));
    }

下图显示了输出 enter image description here

我是条形图的新手,我花了很多时间。这对解决我的问题有任何帮助。

1 个答案:

答案 0 :(得分:0)

尝试使用update()

 this.databar.data.datasets[0].data = res;
 this.databar.update();

OR

this.databar.data.datasets.forEach((dataset) => {
    dataset.data.push(res);
 });
 this.databar.update();