进行 2 次异步调用并将响应从第一个传递到第二个

Make 2 aynchronous calls and pass the response from the first to the second

我有一个使用 Auth0 的网站,为了确定用户是否是管理员,我在 mongoDB 数据库中为该用户存储了一个字段,并附有我从 python 中读回的相关电子邮件] flask API getUser() 函数中的端点。当用户登录时,我收到 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
}

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

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

或者结合使用 promises 和 await 调用,这样代码将等待直到 promise 得到解决,然后再继续前进

  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 方法。