How To Get Current Users "uid" In Component | Angular 7
Trying to make that each user can create and read his own data. I am working everything same as in this tutorial but its not working as there: https://angularfirebase.com/lessons/managing-firebase-user-relationships-to-database-records/
My database is structured like this:
-|items
-|userId
-|itemId
This is my service:
userId: string;
constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth) {
this.afAuth.authState.subscribe(user => {
if(user) this.userId = user.uid
})
}
And example function in service that gets items from database:
getRelays(): Observable<any[]> {
if(!this.userId) return;
this.relaysRef = this.db.list('relays/' + this.userId)
return this.relaysRef.snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ $key: c.payload.key, ...c.payload.val() }))
)
);
}
I want to access that current users id in component so I can get items based on current user but variable userId
only works inside subscription and returns undefined outside it.
This is how i login and logout (in another component):
login() {
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
}
logout() {
this.afAuth.auth.signOut();
}
Thanks for help!
Answer
It's because observables are asynchronus. Since the details of the user are brought in an asynchronous manner. The userId will not be available outside the subscribe method. So you need to write the logic inside the subscribe block inorder to achieve the desired result.
this.afAuth.authState.subscribe(user => {
if(user) this.userId = user.uid
//you have to write the logic here.
})
Related Questions
- → Make a Laravel collection into angular array (octobercms)
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → Angularjs not working inside laravel form
- → Analysis of Flux implementations
- → how to write react component to construct HTML DOM
- → angular ng-repeat and images in a row
- → Conditional BG Color on AngularJS
- → Should I 'use strict' for every single javascript function I write?
- → getting the correct record in Angular with a json feed and passed data
- → "Undefined is not a function" at .toBe fucntion
- → angularjs data binding issue
- → Angular / JavaScript auto hydrate an instance
- → Convert generic text string in json object into valid url using Angular