首页 > 解决方案 > 如何将 API 请求中的数据设置为变量,以便在另一个 API 调用中使用它?

问题描述

我使用 MSAL 登录应用程序。登录后,我调用 Microsoft Graph API 来获取当前用户的电子邮件,然后我想将其传递给另一个 API。每次我尝试传递这些数据时,它都会出现未定义。

这是我在组件中从 Microsoft 调用 API 的方法。

userEmail: string | undefined;

 getProfile(){
    this.http.get(GRAPH_ENDPOINT)
      .subscribe((profile: ProfileType) => {
        this.userEmail = profile.userPrincipalName; //setting userEmail to the returned email address
        console.log(this.userEmail); //logging the email address
      });   
  }

然后,在我的组件的ngOnInit方法中,我写:

 ngOnInit(): void {
      this.getProfile();
      console.log(this.userEmail) //logging the returned email address
 }

这个控制台输出

undefined // the console log from ngOnInit from userEmail
test@microsoft.com // console log from http request

这是我一直遇到的错误,找不到解决方法。我希望能够将 userEmail 设置为从 Microsoft Graph API 返回的帐户电子邮件地址,以便我可以在另一个 API 调用中使用它。

标签: angulartypescriptapimsal

解决方案


在这种情况下,理想的解决方案是使用 Rxjs 运算符 'mergeMap' 链接两个 api 调用。

例子:

this.http
 .get("https://reqres.in/api/users?page=1")
   .pipe(
     mergeMap(users =>
      this.http.get("https://reqres.in/api/users/" + users["data"][1].id)
    )
   )
   .subscribe(res => (this.user = res));

在上面的示例中,我们从 api 获取用户列表,然后将用户 id 从它传递到第二个 api 以获取用户详细信息。

Stackblitz - https://stackblitz.com/edit/angular-api-call-euz5jq?file=src/app/app.component.ts


推荐阅读