1

我正在使用 ng2-charts - https://github.com/valor-software/ng2-charts

我有一个饼图,如果我在我的 component.ts 文件顶部声明变量时对数据进行硬编码,就像我的饼图显示的示例一样。

但我显然想让饼图数据动态化。我可以通过一个服务(是一个数字)调用数据,将数字添加到数据数组中,饼图不起作用。但是,如果我执行控制台日志,则数组会打印出我添加到其中的新数据/数字。

我需要以某种方式重新绘制表格。想不通怎么弄。

 public pieChartLabels:string[] = ['Red Flags','Green Flags'];
 public pieChartData: number[] = [200, 400];
 public chartType:string = 'pie';
 public redFlagsTotal: any;
 public greenFlagsTotal: any;

constructor(private dataService:flagService) {
    let component = this;
    this.redFlagsTotal =    this.dataService.getRedFlags().then(function(result){
        component.redFlagsTotal = result.length;
        console.log(component.redFlagsTotal);
        component.pieChartData.push(component.redFlagsTotal);
        console.log(component.pieChartData);
    });

    this.greenFlagsTotal =     this.dataService.getGreenFlags().then(function(result){
        component.greenFlagsTotal = result.length;
        console.log(component.greenFlagsTotal);
        component.pieChartData.push(component.greenFlagsTotal);
        console.log(component.pieChartData);
    });
}
4

4 回答 4

3

您可以像这样隐藏和显示图表一毫秒:

refreshChart(){
    this.mychart.show = false;
    setTimeout(()=>{
        this.mychart.show = true;
    },1);
}

在模板中使用比mychart.show这样*ngIf的:

<div style="display: block">
  <canvas baseChart
          *ngIf="mychart.show"
          [data]="pieChartData"
          [labels]="pieChartLabels"
          [chartType]="pieChartType"
          (chartHover)="chartHovered($event)"
          (chartClick)="chartClicked($event)"></canvas>
</div>

在您的功能中,您可以refreshChart()在想要刷新图表时使用该功能。

编辑:

如果您重新初始化数组,则 char 应该会自动更新,而不是这样:

component.pieChartData.push(component.greenFlagsTotal);

做这个:

let temp = [...component.pieChartData, ...component.greenFlagsTotal];
component.pieChartData = [...temp];
于 2017-06-28T16:26:18.820 回答
2

解决了!隐藏画布,直到数据加载完毕。

    <div *ngIf="pieChartData.length > 1" style="display: block">
    <canvas baseChart
            [data]="pieChartData"
            [labels]="flagPieChartLabels"
            [chartType]="chartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>
</div>
于 2017-02-23T11:37:09.370 回答
1

使图表数据动态化的另一种方法是通过 ViewChild 绑定图表指令,如下所示:

...
export class HomeComponent {
    @ViewChild(BaseChartDirective)
    public chart: BaseChartDirective;


void updateChart() {
    this.chart.chart.update(); // This re-renders the canvas element.
}

现在,您可以在updateChart每次数据集发生更改时调用以使图表保持最新!

于 2017-06-26T19:30:59.727 回答
0

使用 *ngIf 隐藏画布重新加载整个组件。

似乎如果您推送数据和标签然后在 1 毫秒后删除它们,它将重新加载正确的图表数据。

  reloadChart(){
    this.pieChartLabels.push('reload');
    this.pieChartData.push(1);
    setTimeout(() => {
      this.pieChartData.pop();
      this.pieChartLabels.pop();
    },1);
  }
于 2021-04-15T09:44:35.447 回答