我現在開始與Angular2一起工作,並對框架ng2-charts有疑問。Angular2使用標籤更新ng2圖表
這裏是我的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());
}
}
實際上,當我深入瞭解我的代碼時,HTML組件在開始時接受了變量並更新它們。因此,當標籤爲空時,即使我添加了一些標籤,它們也會被添加爲未定義的標籤。所以我有一個正確的值的圖表,但沒有正確的標籤。一切標記爲未定義。
如果我在一開始啓動的標籤,我會用正確的價值觀
良好的彩色圖表所以我的問題是:
如何加載數據,然後渲染HTML零件 ?
無論如何渲染沒有數據的chart.js組件並用正確的標籤和數據更新它?
任何幫助是必要的,謝謝。
我從Web服務將數據作爲圖表數據源同樣的問題。 –
非常感謝,對我來說工作得很好。我剛看到答案:)。我用了一個ngIf來測試是否有數據,它的工作 – ben
感謝我的工作.. –