ChartJS Angular 图未填充来自API响应的数据

vfhzx4xs  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(137)

我面临着一个挑战,在我的Angular 应用程序中绘制ChartJ的条形图,数据来自我的API响应
这是代码片段

<div class="canvas">
  <canvas id="canvas" baseChart [data]="barChartData" [options]="barChartOptions" [plugins]="barChartPlugins"
    [legend]="barChartLegend" [type]="'bar'">
  </canvas>
</div>
this.barChartData = new Chart('canvas', {
      type:"bar",
      data:  {
        labels: ["Private", "NASHA", "NHIS", "Others"],
        datasets:[{
            data: [ 
              this.apiResponse?.Private,
              this.apiResponse?.data_1
            
            ],
           
            label: 'hey',
            backgroundColor: [ '#E8E2F4']
             
        
        }]
      },
      options:{
        scales: {
          y:{
            beginAtZero:true
          }
        }
      }
      
    })

现在的问题是,图表不是pupolating,当我控制API响应之前创建的图表我得到的值,但当我控制的值后,图表,它返回undefined
请问是什么原因造成的,我该如何修复它

dnph8jn4

dnph8jn41#

由于apiResponse是来自API的响应,因此您应该订阅observable并将响应值分配给apiResponse
根据您当前的代码,我担心的是,当您使用NG 2-Charts指令时,您没有正确地将值传递给这些输入,例如[data][options]

解决方案1:使用NG 2-图表

barChartData应该是ChartData<'bar'>类型,而不是ChartConfiguration<'bar'>

barChartData!: ChartData<'bar'>;
barChartOptions!: ChartOptions<'bar'>;
barChartPlugins!: any;
barChartLegend = true;

this.barChartOptions = {
  scales: {
    y: {
      beginAtZero: true,
    },
  },
};

of({
  Private: 6,
  data_1: 15,
}) /* Replace this with the observable that you call the API */
  .subscribe((resp) => {
    this.apiResponse = resp;

    this.barChartData = {
      labels: ['Private', 'NASHA', 'NHIS', 'Others'],
      datasets: [
        {
          data: [this.apiResponse?.Private, this.apiResponse?.data_1],
          label: 'hey',
          backgroundColor: ['#E8E2F4'],
        },
      ],
    };
  });

解决方案2:Pure Chart.js

对于纯Chart.js,您可以执行以下操作:

of({
  Private: 6,
  data_1: 15,
}) /* Replace this with the observable that you call the API */
  .subscribe((resp) => {
    this.apiResponse = resp;

    new Chart('canvas2', {
      type: 'bar',
      data: {
        labels: ['Private', 'NASHA', 'NHIS', 'Others'],
        datasets: [
          {
            data: [this.apiResponse?.Private, this.apiResponse?.data_1],
            label: 'hey',
            backgroundColor: ['#E8E2F4'],
          },
        ],
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
          },
        },
      },
    } as ChartConfiguration<'bar'>);
  });

Demo @ StackBlitz

相关问题