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.