作者:君琪2010_207 | 来源:互联网 | 2023-02-07 16:42
我现在开始使用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
该component.html代码:
服务代码:
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组件并用正确的标签和数据更新它?
需要任何帮助,谢谢.
1> jordanwillis..:
在标准chart.js中,您可以在.update()
修改其数据(包括标签)后使用原型方法重新渲染图表.
但是,似乎ng2-charts没有提供触发更新的机制(根据这个github问题).我根本没有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
然后您将ngIf
在component.html代码中使用.