我需要在饼图中显示我的用户类型。 我正在使用Angular2,Chart.js和ng2-charts。
dashboard.component.ts:
export class DashboardComponent implements OnInit {
employees = {};
public countFree : number = 0;
public countPaid : number = 0;
public chartData: Array<Object> = [];
public chartLabels: Array<Object> = [];
constructor(private dashboard: DashboardService) { }
ngOnInit() {
this.dashboard.fetchData('http://localhost:8080/employees').subscribe(res => {
res.forEach(function (eachObj) {
if(eachObj.usertype=='Free')
this.countFree++;
else
this.countPaid++;
}.bind(this));
this.chartLabels = ['Paid Users', 'Free Users'];
this.chartData = [{ data: [this.countPaid, this.countFree++] }];
});
}
}
dashboard.component.html:
<div style="width: 40%;">
<canvas
baseChart
[chartType]="'pie'"
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="true"
</canvas>
</div>
我收到错误“ TypeError:无法读取未定义的属性'data'”。 如果我将图表代码放在fetchData()之外,则可以正常工作。 但是我需要countFree和countPaid才能显示为图表数据。
需要别人的帮助。
答案 0 :(得分:0)
可能不是最好的解决方案,但是您可以尝试以下方法:
<div style="width: 40%;" *ngIf="chartData">
<canvas
baseChart
[chartType]="'pie'"
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="true"
</canvas>
</div>
答案 1 :(得分:0)
首先需要确保ng2-charts库和Chart.js库作为依赖添加:
npm install ng2-charts
npm install chart.js
在我们的 Angular 应用程序中使用 ng2-charts 指令,我们需要确保添加 ChartsModule。因此首先在 app.module.ts 中添加以下 import 语句:
app.module.ts
import { ChartsModule } from 'ng2-charts';
imports: [
BrowserModule,
RouterModule.forRoot(routes),
ChartsModule
],
app.component.html
<div class="container-fluid">
<div class="panel panel-body">
<div class="row">
<div class="col-md-12">
<h4>Pie Chart</h4>
<div style="display: block">
<canvas baseChart
[data]="pieChartData"
[labels]="pieChartLabels"
[chartType]="pieChartType"></canvas>
</div>
</div>
</div>
</div>
</div>
app.component.ts
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public pieChartOptions: ChartOptions = {
responsive: true,
};
public pieChartLabels = ['Male', 'Female'];
public pieChartData = [60, 40];
public pieChartType = 'pie';
}
希望这对你有用