angular - 函数中多个可观察调用的返回值
问题描述
我有一个当前正在运行的功能。调用此函数时,它会在组件中设置一个值。(user.userImage)
getLoggedInUserPhoto() {
this.adalService.acquireToken('https://graph.microsoft.com')
.subscribe(token => {
let header = new HttpHeaders().set('Authorization', 'Bearer ' + token).set('Content-Type', 'image/jpeg');
this.imageService.getImage('https://graph.microsoft.com/v1.0/me/photo/$value', header)
.subscribe(blob => {
this.imageService.getImageUrlFromBlob(blob)
.then(res => {
this.user.userImage = res;
})
})
});
}
我试图用一个新函数做同样的事情,除了我希望函数返回值而不是在组件中设置值。我已经搜索过了,很可能我使用了错误的搜索词。但是,这是我想要实现的目标
getPhoto(email: string): string {
return this.adalService.acquireToken('https://graph.microsoft.com')
.subscribe(token => {
let header = new HttpHeaders().set('Authorization', 'Bearer ' + token).set('Content-Type', 'image/jpeg');
this.imageService.getImage('https://graph.microsoft.com/v1.0/users/'+email+'/photo/$value', header)
.subscribe(blob => {
this.imageService.getImageUrlFromBlob(blob)
.then(res => {
return res;
})
})
});
}
解决方案
我建议您使用switchMap
,因为 switchMap 运算符将等待第一个请求的响应到达,然后再触发第二个请求。
return this.http.get('https://graph.microsoft.com')
.switchMap(res1 => {
// use res1 to further control param of the second call
this.http.get(''https://graph.microsoft.com/v1.0/users/'+email+'/photo/$value', header')
})
.subscribe(res2 => {
//do stuff with the second response
})
推荐阅读
- javascript - Elasticsearch - 在评分结果时找到最接近的数字
- python - ubuntu 环境下项目设置错误
- c# - 无法将 wpf 中的数据网格转换为 csv 而不会丢失阿拉伯值
- python - 在输入功能中,如何确保用户只输入精确到小数点后 2 位的数字?
- faunadb - 如何使用 FaunaDB Shell 打开我的子数据库?
- python - 如何通过在后台检测到按键来打破无限循环?
- c - 使用结构从另一个函数调用变量
- c++ - 在带有 LLD 的 Windows 10 上使用 Clang
- r - 避免覆盖 data.table 函数中的现有列
- mysql - mysql:外键不起作用?存在不应该存在的记录