带有angular2的图表js仅在zoomin之后加载动态数据

时间:2017-02-08 11:36:25

标签: angular chart.js

我正在开发一个带有chartjs的角度2应用程序,用馅饼,甜甜圈显示一些数据。

我能够使用静态数据渲染图表,但不能使用动态数据。它仅在zoomin之后呈现动态数据。

请你协助我解决这个问题,并帮助我们一次性动态呈现数据。

组件html:

import { Component, Input } from '@angular/core';
import { PaymentModeServiceComponent } from '../../services/paymentmode/paymentmode-service.component';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Observable';
import { PaymentMode } from '../../domain/paymentmode';

@Component({
  selector: 'app-paymentmode',
  templateUrl: './paymentmode.component.html',
  providers: [PaymentModeServiceComponent]
})
export class PaymentModeComponent {

   paymentModes: Array<PaymentMode> = [];
   
         // Doughnut
  private doughnutChartLabels:string[]=["sdsd"];
  doughnutChartData:number[]=[1,1,1,1,1,1,1,1,1,1 ];
  public doughnutChartType:string = 'doughnut';

  
  public lineChartColors:Array<any> = [{
                backgroundColor: [
                "#0000ff",
                "#ff0000",
                "#00ff00",
                "#728885",
                "#f98885",
                "#f9fc4b"
  ]}
            ];
            
   public legend:boolean = false;
  
   constructor(dataService: PaymentModeServiceComponent) {
    dataService.getPaymentModes().subscribe(
          paymentMode => this.paymentModes = paymentMode,
      );
  }
  
  
  getDoughnutChartLabels() {
  	for (let i = 0; i < this.paymentModes.length; i++) {
  		let paymentMode = this.paymentModes[i];
  		this.doughnutChartLabels[i] = paymentMode.paymentMode;
	  }
	  return this.doughnutChartLabels;
   }
   
   getDoughnutChartData() {
  	for (let i = 0; i < this.paymentModes.length; i++) {
  		let paymentMode = this.paymentModes[i];
  		this.doughnutChartData[i] = paymentMode.paymentModeTotalSales;
	  }
	  
	  //this.doughnutChartData.splice(this.doughnutChartLabels.length + 1, this.doughnutChartData.length - this.doughnutChartLabels.length);
	  
	  //this.doughnutChartData = this.doughnutChartData.slice();
	  
	  return this.doughnutChartData;
   }
  

}

组件ts文件:

&#13;
&#13;
X_train
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

我在使用Angular 2和许多图表包时遇到了这个问题,我通常要做的就是按照以下几行:

(1)绑定到尚未实例化的集合

HTML: [data]="doughnutChartData" ; TS: doughnutChartData:number[]

(2)在图表标记中添加ngif,例如

<canvas baseChart  *ngIf="doughnutChartData && doughnutChartData.length > 0" ....>

(3)在ng init上运行你的getDoughnutChartData功能。使用您getDoughnutChartData函数中的本地集合来收集数据。当数据返回/完成时doughnutChartData = localDoughnutChartData

使用ngif表示在您拥有数据之前不会尝试渲染图表

你可以在它上面添加一个包含微调器的DIV,并且具有相反的ngif,因此在制作图表数据时会显示微调器。 *ngIf="!doughnutChartData || doughnutChartData.length < 1"

答案 1 :(得分:0)

这就像一个魅力

  <canvas *ngIf="doughnutChartData && doughnutChartData.length > 0" baseChart
  [data]="doughnutChartData"
  [labels]="doughnutChartLabels"
  [chartType]="doughnutChartType"
  [options]="barChartOptions"></canvas>