Angular2更新ng2图表,标签为

时间:2017-04-04 10:00:40

标签: javascript angular charts chart.js ng2-charts

我现在用 Angular2 开始工作,并对框架 ng2-charts 提出疑问。

这是我的 component.ts 代码:

import { Component } from '@angular/core';
import { ChartsModule } from 'ng2-charts';
import { PredictionService } from './prediction.service'

@Component({
  selector: 'prediction-result-chart',
  templateUrl: './predictionResultChart.component.html'
})

export class PredictionResultChartComponent{

  public pieChartLabels:string[] = [];
  public pieChartData:number[] = [];
  public pieChartType:string = 'pie';
  public JSONobject = {}

  constructor(private predictionService: PredictionService){
    this.getPredictions();
  }

  public getPredictions() {
    this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe();
  }

  public populateChart(obj): void{
    let labels:string[] = [];
    let data:number[] = [];
    for (var i = 0; i < obj.predictions.length; i++)
    {
      labels.push(String(obj.predictions[i].class));
      data.push(obj.predictions[i].percentage);
    };
    this.pieChartData = data;
    this.pieChartLabels = labels;
  }

  public chartClicked(e:any):void {}
  public chartHovered(e:any):void {}

}

component.html 代码:

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

服务代码:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';

import { Observable }     from 'rxjs/Observable';
import 'rxjs/add/operator/map';


@Injectable()
export class PredictionService {

  private baseUrl: string = 'http://localhost:8080/predict/';
  constructor(private http : Http){
  }

  getPredictions(text :string) {
    return this.http.get(this.baseUrl + text).map(res => res.json());
  }

}

使用上面的代码,这是我所拥有的,没有任何颜色的图表:enter image description here

事实上,当我深入研究我的代码时,HTML组件在开始时获取变量然后更新它们。因此,当标签为空时,即使我添加了一些标签,它们也会被添加为未定义。所以我有一个图表,其中包含正确的值,但没有正确的标签。标记为未定义的所有内容。

如果我在开始时启动标签,我将会有一个带有正确值的好彩色图表

所以我的问题是:

  

如何加载数据,然后呈现HTML组件?

     

是否有渲染chart.js组件没有数据并使用正确的标签和数据进行更新?

需要任何帮助,谢谢。

4 个答案:

答案 0 :(得分:11)

在标准chart.js中,您可以使用.update()原型方法在修改数据(包括标签)后重新渲染图表。

但是,似乎ng2-charts没有提供触发更新的机制(按照this github issue)。我根本没有Angular2的经验,但也许这对你有用吗?该方法取自zbagley在17天前发布的github问题中发表的评论(遗憾的是,我无法找到一种方法来生成引用此特定评论的网址)。

方法是在数据可用之前基本上不渲染图表。以下是对 component.ts 代码的更改。

import { Component } from '@angular/core';
import { ChartsModule } from 'ng2-charts';
import { PredictionService } from './prediction.service'

@Component({
  selector: 'prediction-result-chart',
  templateUrl: './predictionResultChart.component.html'
})

export class PredictionResultChartComponent {    
  public pieChartLabels:string[] = [];
  public pieChartData:number[] = [];
  public pieChartType:string = 'pie';
  public JSONobject = {};
  public isDataAvailable:boolean = false;

  constructor(private predictionService: PredictionService){
    this.getPredictions();
  }

  public getPredictions() {
    this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe();
  }

  public populateChart(obj): void {        
    let labels:string[] = [];
    let data:number[] = [];
    for (var i = 0; i < obj.predictions.length; i++)
    {
      labels.push(String(obj.predictions[i].class));
      data.push(obj.predictions[i].percentage);
    };
    this.pieChartData = data;
    this.pieChartLabels = labels;
    this.isDataAvailable = true;
  }

  public chartClicked(e:any):void {}
  public chartHovered(e:any):void {}    
}

然后您将在 component.html 代码中使用ngIf

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

答案 1 :(得分:1)

我可以在打印到控制台时获取值,但不会在图表上显示。

this.pieChartLabels :: ['PayDirect agent deposit','GtCollections agent deposit','Quickteller agent deposit']
this.pieChartData :: [1990,1202,2476]

有没有办法更新图表。似乎在从Web服务收到数据之前加载了图表。

isDataAvailable2 = true

但图表从未加载。

答案 2 :(得分:1)

我通过更新配置属性中的标签更新了图表标签。

import { Component } from '@angular/core';
import { ChartsModule } from 'ng2-charts';
import { PredictionService } from './prediction.service'
import { BaseChartDirective } from 'ng2-charts'; // ----- added

@Component({
  selector: 'prediction-result-chart',
  templateUrl: './predictionResultChart.component.html'
})

export class PredictionResultChartComponent {    
  public pieChartLabels:string[] = [];
  public pieChartData:number[] = [];
  public pieChartType:string = 'pie';
  public JSONobject = {};
  public isDataAvailable:boolean = false;

  @ViewChild('mainChart') mainChart: BaseChartDirective; // ----- added

  constructor(private predictionService: PredictionService){
    this.getPredictions();
  }

  public getPredictions() {
    this.predictionService.getPredictions('hello').do(result => 
    this.populateChart(result)).subscribe();
  }

  public populateChart(obj): void {        
    let labels:string[] = [];
    let data:number[] = [];
    for (var i = 0; i < obj.predictions.length; i++)
    {
      labels.push(String(obj.predictions[i].class));
      data.push(obj.predictions[i].percentage);
    };
    this.pieChartData = data;
    this.mainChart.chart.config.data.labels = labels; // ---- updated
    this.isDataAvailable = true;
  }

  public chartClicked(e:any):void {}
  public chartHovered(e:any):void {}    
}

在HTML中添加#{chartName}以访问它

<div style="display: block" *ngIf="isDataAvailable">
  <canvas #mainChart="base-chart" baseChart
      [data]="pieChartData"
      [labels]="pieChartLabels"
      [chartType]="pieChartType"
      (chartHover)="chartHovered($event)"
      (chartClick)="chartClicked($event)"></canvas>
</div>

答案 3 :(得分:0)

首先要确保标签的顺序与data_set的顺序相匹配,所以基本上你有这两个变量:

private datasets_pie = [
    {
        label: "Commissions",
        data: Array<any>(),
        backgroundColor: Array<any>()
    }
];
private labels_pie = Array<any>();

其次我对颜色有同样的问题,所以我不得不手动插入颜色,这是一个例子:

private chartColors: any[] = [{ backgroundColor: ["#FFA1B5", "#7B68EE", "#87CEFA", "#B22222", "#FFE29A", "#D2B48C", "#90EE90", "#FF69B4", "#EE82EE", "#6A5ACD", "#b8436d", "#9ACD32", "#00d9f9", "#800080", "#FF6347", "#DDA0DD", "#a4c73c", "#a4add3", "#008000", "#DAA520", "#00BFFF", "#2F4F4F", "#FF8C00", "#A9A9A9", "#FFB6C1", "#00FFFF", "#6495ED", "#7FFFD4", "#F0F8FF", "#7FFF00", "#008B8B", "#9932CC", "#E9967A", "#8FBC8F", "#483D8B", "#D3D3D3", "#ADD8E6"] }];

最后在正确创建这些对象之后,你必须调用这个函数:

setTimeout(() => {
            if (this.chart && this.chart.chart && this.chart.chart.config) {
                this.chart.chart.config.data.labels = this.labels_pie;
                this.chart.chart.config.data.datasets = this.datasets_pie;
                this.chart.chart.config.data.colors = this.chartColors;
                this.chart.chart.update();
            }
            this.sommeStat = this.getSomme();
        });

所以我认为这可能会奏效:

    import { Component, ViewChild, ElementRef } from '@angular/core';
    import { ChartsModule } from 'ng2-charts';
    import { PredictionService } from './prediction.service';
    import { BaseChartDirective } from 'ng2-charts/ng2-charts';

    @Component({
      selector: 'prediction-result-chart',
      templateUrl: './predictionResultChart.component.html'
    })

    export class PredictionResultChartComponent{
        @ViewChild(BaseChartDirective) chart: BaseChartDirective;

      public pieChartType: string = 'doughnut';
        //public lineChartType: string = 'line';

        private datasets_pie = [
            {
                label: "Commissions",
                data: Array<any>(),
                backgroundColor: Array<any>()
            }
        ];
        private labels_pie = Array<any>();

        //private datasets_line : LineData[] = [];
        // private datasets_line : { label : string, data : Array<any>}[] ;
        // private labels_line = Array<any>();

        private chartColors: any[] = [{ backgroundColor: ["#FFA1B5", "#7B68EE", "#87CEFA", "#B22222", "#FFE29A", "#D2B48C", "#90EE90", "#FF69B4", "#EE82EE", "#6A5ACD", "#b8436d", "#9ACD32", "#00d9f9", "#800080", "#FF6347", "#DDA0DD", "#a4c73c", "#a4add3", "#008000", "#DAA520", "#00BFFF", "#2F4F4F", "#FF8C00", "#A9A9A9", "#FFB6C1", "#00FFFF", "#6495ED", "#7FFFD4", "#F0F8FF", "#7FFF00", "#008B8B", "#9932CC", "#E9967A", "#8FBC8F", "#483D8B", "#D3D3D3", "#ADD8E6"] }];

        private options = {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        };
      public JSONobject = {}

      constructor(private predictionService: PredictionService){
        this.getPredictions();
      }

      public getPredictions() {
        this.predictionService.getPredictions('hello').do(result => this.populateChart(result)).subscribe();
      }

      public populateChart(obj): void{

        this.labels_pie = [];
        this.datasets_pie[0]['data'] = [];
        for (var i = 0; i < obj.predictions.length; i++)
        {
          labels.push(String(obj.predictions[i].class));
          this.datasets_pie[0]['data'].push(obj.predictions[i].percentage);
        };
let arrColors: any[];
        arrColors = arrColorsCopy.splice(0, this.products.length);
        this.datasets_pie[0]['backgroundColor'] = arrColors;

        setTimeout(() => {
                if (this.chart && this.chart.chart && this.chart.chart.config) {
                    this.chart.chart.config.data.labels = this.labels_pie;
                    this.chart.chart.config.data.datasets = this.datasets_pie;
                    this.chart.chart.config.data.colors = this.chartColors;
                    this.chart.chart.update();
                }
            });
      }

      public chartClicked(e:any):void {}
      public chartHovered(e:any):void {}

    }

对于HTML应该看起来像这样:

<div class="col-md-8">
                <div class="chart">
                    <canvas baseChart [datasets]="datasets_pie" [labels]="labels_pie" [chartType]="pieChartType" [colors]="chartColors"> </canvas>
                </div>
            </div>

这就是全部,你应该尝试这种方式,它应该工作