【问题标题】:Make 2 aynchronous calls and pass the response from the first to the second [duplicate]进行2次异步调用并将响应从第一个传递到第二个[重复]
【发布时间】:2020-04-12 23:01:09
【问题描述】:

我有一个使用 Auth0 的站点,为了确定用户是否是管理员,我在我的 mongoDB 数据库中为该用户存储了一个字段,并附有他们的关联电子邮件,我在 getUser() 函数中从我的 python 烧瓶 API 端点读回了这些电子邮件.当用户登录时,我收到 Auth0 用户电子邮件的响应并将相关字段传递到 getUser() 函数,但是,我无法想出一个链接这些调用的解决方案。到目前为止,我已经尝试过使用承诺和订阅,但无济于事。

web.service.ts

getUser(email) {
        return this.http.get('http://localhost:5000/api/v1.0/user/' + email).subscribe(resp => {
            this.user_info = resp;
        });
    }

home.component.ts

export class HomeComponent { 
    constructor(private authService: AuthService,
                private webService: WebService) {}

    user_email;
    is_admin;

    ngOnInit() {

      this.authService.userProfile$.subscribe(resp => {
          if (resp != null) {
            this.user_email = resp.email
          }
      }); //after this aync call is completed, I want to pass the user_email into the getUser()
          //function and set is_admin depending on the response
}

【问题讨论】:

标签: angular typescript auth0


【解决方案1】:
  this.authService.userProfile$.pipe(switchMap((resp) => this.webService.getUser(resp.email))).subscribe((resp) => {
    this.is_admin = resp.is_admin;
  });

  getUser(email) {
    return this.http.get('http://localhost:5000/api/v1.0/user/' + email)
  } // Dont subscribe here to compose as done above

您始终可以使用运算符从一个流组合到另一个流。在这里,我将userProfile$ 流映射到getUser() 流。我在这里使用switchMap 运算符,如果您的userProfile$ 流在api 处于进行状态时发出值,它将取消getUser 方法。

【讨论】:

    【解决方案2】:

    您可以在收到来自 Auth 服务的响应后执行您的链:即:

      this.authService.userProfile$.subscribe(resp => {
          if (resp != null) {
            this.user_email = resp.email;
            this.getUser(this.user_email);
          }
      });
    

    或者结合使用 Promise 和 await 调用,这样代码会一直等待,直到 Promise 解决后再继续前进

    【讨论】:

    • 您的方法是订阅中的订阅,这是一种反模式。
    猜你喜欢
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多