首页 > 解决方案 > 来自 component.ts 的数据不会在 Angular 应用程序的 component.html 中获取

问题描述

我编写了一个简单的 Angular 应用程序,它将从 REST Api 获取数据并绘制饼图。在我的 app.component.ts 文件中,我得到这样的数据

 this.satisfactionService.getGenderDetails().subscribe(result =>{ 

   this.Data=result;  

   console.log(this.Data)
   console.log(Object.keys(this.Data).length)
   console.log(this.Data.labels)
   console.log(this.Data.values) 

   this.flag=true;

   console.log(this.Data)

   if (typeof(this.Data) != "undefined") {   

     this.pieChartLabels = this.Data.labels;
     this.pieChartData=this.Data.values;
     this.pieChartType= 'pie';

     console.log(this.pieChartLabels )
     console.log(this.pieChartData)

     this.flag=false;
   }

 }, error => console.log(error)); 

在我的 app.component.html 文件中,我正在根据数据绘制饼图

<div class="otherBox" >
  <div class="vamBox">
    <div style="text-align:center;">     
      <span>
        <p class="cardText">Distribution of Students Based on Gender</p>
      </span>
    </div>
  </div>
  <div class="vamInfoBox">
    <canvas baseChart height="100px"
      [data]="pieChartData"
      [labels]="pieChartLabels"
      [chartType]="pieChartType">
    </canvas>
  </div>
</div>

使用 Chrome 工具进行调试时出现此错误 在此处输入图像描述

标签: angularsubscribe

解决方案


在组件尝试渲染图表后肯定会获取数据,您可以添加一个简单的 ****ngIf*** 指令来检查pieChartDate是否可用

<canvas *ngIf='pieChartData'></canvas>

推荐阅读