0

I am using firebase auth and when a user logs it, I'm trying to get his uid (key) and save it.

This is my code (Here console.log(that.uid); returns the key):

 loginWithEmail(email, password) 
  {
    // Resolving scope problems in TypeScript
    let that = this;

    return this.af.auth.login(
    {
      email: email,
      password: password
    },
    {
      provider: AuthProviders.Password,
      method: AuthMethods.Password,
    }).then((user) => 
      {
        that.uid = user.uid;
       // console.log(that.uid);
      })
  } 

and I have a function that gets called from another component that returns the uid:

getUid()
  {
    console.log(this.uid);
    return this.uid;
  } 

Here console.log(this.uid); returns 'undefined'.

Why does it happen and how can I resolve it?

EDIT:

I was read the answers below and understand that the problem is with async.. but I didn't find a solution how to save my data (in this example: user id) from async function to sync one.

I will be glad if someone can offer a solution to my code so I will be able to understand how to fix it and to use well async and sync.

EDIT2:

getUid() function is provide inside afservice whith the loginWithEmail(email, password) function. getUid() was called from another component, in my case HomeComponent in this way:

export class HomeComponent implements OnInit 
{

   permission: number;

  constructor(private afService: AF, private router: Router) 
  { 
            console.log(afService.getUid());
  }
}

thanks.

  • 2
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – JJJ May 17 '17 at 16:24
  • Where is `getUid()` defined? Can you provide more details about this – Bharadwaj May 19 '17 at 09:25
  • I was edited my question, thanks – JavaBeginner May 19 '17 at 11:05

0 Answers0