[Fixed] How do I set data from an API request to a variable so that I can use it in another API call?

Issue

I use MSAL to log in to the application. Once logged in, I call the Microsoft Graph API to get the current user’s email which I then want to pass to another API. Every time that I try to pass this data, it comes out undefined.

This is the method that I have in my component to call the API from Microsoft.

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
      });   
  }

Then, in my component’s ngOnInit method I write:

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

This console outputs

undefined // the console log from ngOnInit from userEmail
[email protected] // console log from http request

This is the error I keep running into and cannot find a work around. I want to be able to have userEmail set to the Account email address that is return from the Microsoft Graph API so that I can use it in another API call.

Solution

In this situation the ideal solution is to use Rxjs operator ‘mergeMap’ to chain two api calls.

Example:

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));

In the above example we are getting the list of users from the api and then passing the user id from it to the second api to get the user details.

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

Leave a Reply

(*) Required, Your email will not be published