How to await subscribe in Angular

I have a function that suppose to return the user’s info from an API

    getUser(){
      const token = localStorage.getItem("user");
      const tokenJson = JSON.parse(token as string);
      const email = tokenJson.user.email;
      const uid = tokenJson.user.uid;

      this.http.get(this.url + uid).subscribe((res: any) => {
        const user = {
          userId: uid,
          email: email,
          fName: res.fName,
          lName: res.lName,
        }
        return user;
      })   
    }

But the problem is that, when I call the function, I get undefined

   console.log(this.auth.getUser());

I tried to solve the problem by assigning the value to a variable, and then I accessed the variable directly (Same issue)

   this.auth.getUser();
   console.log(this.auth.userInfo);

But finally, when I settimeout it works

   this.auth.getUser();
   setTimeout(() => {
      console.log(this.auth.userInfo);
   }, 1000);

now I’m sure it’s an asynchronous issue
How can I wait for the result?
and what’s the best way to solve this problem?

  • 1

    Does this answer your question? Angular 2: Convert Observable to Promise

    – 

you just need to change the way you consume getUser method.

Think of it like this, fetching user from an API is an asynchronous action in nature and as your getUser method is performing that action, you need to wait for it to complete, now how do you do that?

getUser() {
    const token = localStorage.getItem("user");
    const tokenJson = JSON.parse(token as string);
    const email = tokenJson.user.email;
    const uid = tokenJson.user.uid;

    return this.http.get(this.url + uid).pipe(
        map(res => ({
            userId: uid,
            email: email,
            fName: res.fName,
            lName: res.lName,
        }))
    );
}

Now instead of subscribing to the observable inside getUser, you’re returing an Observable to which you can subscribe to and do something after you get the response back like this:

this.auth.getUser().subscribe(res => console.log(res));

or like this:

// this is new syntax that rxjs recommends
this.auth.getUser().subscribe({ next: res => console.log(res) });

Leave a Comment