我试图在订阅之外的函数中使用从Angular Observable Service返回的数据。我可以成功访问“视图组件”(.html)中的数据,但是当我无法从component.ts文件中的另一个函数访问数据时。尝试从下面的“ drawChart”函数访问时,该值以“ undefined”形式返回。
如何从drawChart函数访问expertCount数据?
我的组件代码如下: dashboard.component.ts
ngOnInit() {
this.getUserCounts();
this.drawCharts();
}
getUserCounts() {
this.userService.getUserCount('all').subscribe(totalUserCount => { this.totalUserCount = totalUserCount; });
this.userService.getUserCount('specialist').subscribe(specialistCount => { this.specialistCount = specialistCount; });
this.userService.getUserCount('delegate').subscribe(delegateCount => { this.delegateCount = delegateCount; });
this.userService.getUserCount('practioner').subscribe(practionerCount => { this.practionerCount = practionerCount; });
this.userService.getUserCount('admin').subscribe(adminCount => { this.adminCount = adminCount; });
}
drawCharts() {
console.log('The valiue:' + this.specialistCount);
this.pieChartData = {
chartType: 'PieChart',
dataTable: [
['Users', 'Hours per Day'],
['Specialists', this.specialistCount],
['Delegates', this.delegateCount],
['practioners', 15],
['QMS Staff', 0]
],
options: {'title': 'Users'},
};
}
我的服务代码是: user.service.ts
getUserCount(role) {
const headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get(this.apiUrl + '/users/count/' + role, { headers: headers }).map(res => res.json());
}
答案 0 :(得分:2)
我正在尝试在订阅之外的函数中使用从Angular Observable Service返回的数据。
您不能这样做。这是因为HTTP观察值是异步的。
let foo
console.log('before', foo)
this.https.get('something').subscribe(result => {
foo = result
console.log('inside', foo)
})
console.log('after', foo)
假设观察对象返回数字42(result
为42),则将输出以下内容:
before undefined
after undefined
inside 42
前两行将立即打印。仅在浏览器将请求发送到服务器,请求通过地球上的电缆传输到服务器,响应到达并将其解析为JSON之后,才会打印最后一行。
您需要在subscription方法内调用getUserCount
方法。似乎您需要先发出全部五个请求,然后才能有足够的信息来运行getUserCount
函数,因此您需要等待所有五个请求完成才能运行它。
您可以看到here如何进行并行请求。
要并行执行请求 (对于非并行请求 彼此依赖),请使用the
forkJoin
static operator。return Observable.forkJoin( this.http.get('url/1'), this.http.get('url/2'), ) .subscribe(([res1, res2]) => { // res1 and res2 available after both requests are completed })
请注意,这与Angular无关-仅与RxJS和HTTP请求的异步性质有关。
答案 1 :(得分:0)
根据拉扎尔的回答,我已修改代码以使用forkJoin并在Observable中调用populateGrid函数。
新代码如下:
ngOnInit() {
this.getUserCounts();
}
getUserCounts() {
forkJoin(this.userService.getUserCount('all'),
this.userService.getUserCount('specialist'),
this.userService.getUserCount('delegate'),
this.userService.getUserCount('practioner'),
this.userService.getUserCount('admin')
).subscribe(
returnedValues => {
this.totalUserCount = returnedValues[0];
this.specialistCount = returnedValues[1];
this.delegateCount = returnedValues[2];
this.practionerCount = returnedValues[3];
this.adminCount = returnedValues[4];
this.drawCharts();
}
);
}
drawCharts() {
this.pieChartData = {
chartType: 'PieChart',
dataTable: [
['Users', 'Hours per Day'],
['Specialists', this.specialistCount],
['Delegates', this.delegateCount],
['Practioners', this.practionerCount],
['QMS Staff', this.adminCount]
],
options: {'title': 'Users'},
};
}