angular - How to make ng2-google-charts wait for data to load before displaying?
问题描述
I am using ng2-google-charts to display some data in a donut chart in my Angular app. In the app, I pull a user from a JSON server, do some relatively simple calculations, and output the results of those calculations in the donut chart. When data is passed straight into the graph it works fine, but when I pass user information that is calculated into the graph is displays nothing. I suspect this is because it is loading data before the calculations are complete.
I have tried using an *ngIf on the surrounding div to wait for the user to complete loading and calculations to complete, but that seems to do nothing. I know I can probably use the resolved promise to my advantage (I'm using that to make sure the page doesn't load before the data does), but I'm still not really sure how to tie that in with ng2-google-charts. The ng2-google-charts documentation doesn't seem to have any information regarding the matter. I'm still trying to wrap my head around asynchronous functions, so any help would be greatly appreciated.
home.component.ts
userLoaded: Promise<boolean>;
creditsCompleted = 0;
creditsInProgress = 0;
creditsLeft = 0;
getUser() {
this.eventsService.user$.subscribe((user) => {
this.user = user;
if (user) {
this.calculateUserCredits(); // the function that does our calculations
this.userLoaded = Promise.resolve(true);
}
})
}
calculateUserCredits() {
// we calculate stuff and assign to the credits variables
}
public pieChart: GoogleChartInterface = {
chartType: 'PieChart',
dataTable: [
['Task', 'Total Credits'],
['Completed', this.creditsCompleted],
['In Progress', this.creditsInProgress],
['Remaining', this.creditsLeft]
],
options: {'title': 'Credit Breakdown',
'pieHole':0.4,
'pieSliceTextStyle': {
'color':'black'
},
'fontName':'Roboto',
'backgroundColor' : {
'fill' : 'transparent'
}
},
};
home.component.html
<div class="col-lg-8 bodyFont" style="width: 100%; height: 100%">
<google-chart class="p-0 m-0" [data]="pieChart"></google-chart>
</div>
解决方案
你可以像这样从你的方法中返回一个 ObservablecalculatUserCredits
并订阅它:
ngOnInit()
{
this.calculatUserCredits().subscribe(value => {
// do something to trigger your *ngIf here.
});
}
public calculatUserCredits(): Observable<any>{
// return a bool, or even the calculated data.
return of("some value");
}
推荐阅读
- r - as.Date() 函数在 R 中返回 NA
- c# - 不断更改数据和缓存?
- mysql - 如何在没有服务器失败的情况下使用 Laravel eloquent 和 MySql 处理大量记录?
- php - PHP - 如果条件匹配,则删除项目根目录中的所有文件和文件夹
- javascript - 将非函数脚本从 HTML 迁移到 JS 文件
- java - 从 ResultSet 检索元素时出现问题
- amazon-workspaces - Amazon Workspace:从本地计算机上传/下载文件
- hive - `impyla` 连接到 Dataproc 上的 Hive:impala.error.HiveServer2Error: Invalid OperationHandle: OperationHandle
- oracle - ORA 06503 函数返回无值
- python - 当我将布尔数据帧传递给 pandas 中另一个数据帧的索引运算符时会发生什么?