简体   繁体   English

在饼图中异步显示来自 chart.js 和 typescript 的数据

[英]Async showing data in pieChart from chart.js with typescript

I have the following setup in my Angular project:我的 Angular 项目中有以下设置:

HTML HTML

<canvas baseChart 
[data]="pieChartData" 
[labels]="pieChartLabels" 
[colors]="pieChartColours" 
[chartType]="pieChartType">
</canvas>

TS TS

export class ValidationResultComponent implements OnInit {  
...
Success
Allowed
Failed
pieChartLabels:string[] = ['Success', 'Allowed', 'Failed'];
pieChartData:number[] = [this.Success, this.Allowed, this.Failed];
pieChartType:string = 'pie';
pieChartColours:any[] = [{ backgroundColor: ["#bff0aa","#f2e69d", "#e0a2a2"] }]

constructor(
    private notificationService: NotificationService,
    private codeValidationService: CodevalidationService,
    private router: Router,
    private route: ActivatedRoute) { }

ngOnInit() {
    let that = this;

    this.dtOptions[0] = {
      ...
      ajax: (dataTablesParameters: any, callback) => {
        that.codeValidationService.getCodeValidationResults('id')
          .subscribe(
          (responses) => {
            var logDetails = responses['results'][0]['stats'].map( stats => {
              if(stats.action === "# Successful services"){
                this.Success = stats.times
              }
              if(stats.action === "# Failed services"){
                this.Failed = stats.times
              }
              if(stats.action === "# Allowed Exceptions"){
                this.Allowed = stats.times
              }
              return {
                'name': this.checkNull(stats.action),
                'status': this.checkNull(stats.times),
              }
            })
            callback({
              data: logDetails
            })
          })
      }
    };
    ...
}

With this setup, there will not be data shown in my pieChart because I assign the data to the variables from an API call in ngOninit().使用此设置,我的饼图中将不会显示数据,因为我将数据分配给来自 ngOninit() 中 API 调用的变量。 Has anyone got an idea how I can solve this?有谁知道我该如何解决这个问题?

Try using ngOnChanges() to listen to the data change and update your variables accordingly.尝试使用 ngOnChanges() 来监听数据变化并相应地更新你的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM