首页 > 解决方案 > 函数中多个可观察调用的返回值

问题描述

我有一个当前正在运行的功能。调用此函数时,它会在组件中设置一个值。(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;
          })
      })
  });
}

标签: angulartypescriptmicrosoft-graph-apiadal

解决方案


我建议您使用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
  })

推荐阅读