检索从Angular中的函数返回的值



我想用chart.js和ng2chart在Angular中创建一个图表。我已经创建了一个函数来计算要传递到图表的值,但我不能像下面的代码所示那样执行,因为我会在初始化之前使用属性"online"。还有什么方法可以将onlineNumber()函数返回的值传递给doughnutChartData?这就是功能:

online: number;
term: number;
doughnutChartData = [this.online, this.term];
onlineNumber() : number {
this.memberService.onlineUsers().subscribe((number: number) => {
this.online = number;
})
return this.online;
}
userNumber() {
this.memberService.userNumber().subscribe((number: number) => {
this.term = number;
})
}

html:

<div style=" margin-top: -6%; margin-left:15%; width: 50%;">
<canvas baseChart 
[data]="doughnutChartData"
[labels]="doughnutChartLabels"
[chartType]="doughnutChartType"
></canvas>
</div>

您有完整的工作示例吗?

我的猜测是在订阅中初始化甜甜圈图表数据:

online: number;
doughnutChartData;
onlineNumber() : number {
this.memberService.onlineUsers().subscribe((number: number) => {
this.online = number;
doughnutChartData = [this.online, 9];
});
return this.online;
}

更新的答案:添加另一个方法来初始化DoughnutChartData,并在userNumber和onlineNumber:中使用它

initializeDoughnutChartData() {
if (this.online != undefined && this.term != undefined) {
this.doughnutChartData = [this.online, this.term];
}
}

在userNumber和onlineNumber:内调用此方法

onlineNumber() : number {
this.memberService.onlineUsers().subscribe((number: number) => {
this.online = number;
this.initializeDoughnutChartData();
})
return this.online;
}
userNumber() {
this.memberService.userNumber().subscribe((number: number) => {
this.term = number;
this.initializeDoughnutChartData();
})
}

相关内容

  • 没有找到相关文章

最新更新