Reputation: 2084
I'm following along with the AngularFire tutorial here: https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/. My question is: How would I fetch the currently signed in user's UID and displayName in a different component? I'm already importing and injecting AuthService (the service below), but how do I access those fields in Firestore? Below is the relevant code.
@Injectable()
export class AuthService {
user: Observable<User>;
constructor(private afAuth: AngularFireAuth,
private afs: AngularFirestore,
private router: Router) {
//// Get auth data, then get firestore user document || null
this.user = this.afAuth.authState
.switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
} else {
return Observable.of(null)
}
})
}
googleLogin() {
const provider = new firebase.auth.GoogleAuthProvider()
return this.oAuthLogin(provider);
}
private oAuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((credential) => {
this.updateUserData(credential.user)
})
}
private updateUserData(user) {
// Sets user data to firestore on login
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
const data: User = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL
}
return userRef.set(data)
}
signOut() {
this.afAuth.auth.signOut().then(() => {
this.router.navigate(['/']);
});
}
}
Upvotes: 1
Views: 1049
Reputation: 7326
My question is: How would I fetch the currently signed in user's UID and displayName in a different component?
In a different component, you can inject this authService and can use the user
property which is an observable.
if you want to use it in component only:
user: User;
constructor(public auth: AuthService) { }
now you can subscribe on auth.user
eg:
ngOnInit() {
this.auth.user.subscribe((user) => {
this.user = user;
console.log(user)
/* user.uid => user id */
/* user.displayName => user displayName */
})
}
or just in html:
<div *ngIf="auth.user | async as user">
<h3>Howdy, {{ user.displayName }}</h3>
<img [src]="user.photoURL">
<p>UID: {{ user.uid }}</p>
<p>Favorite Color: {{ user?.favoriteColor }} </p>
</div>
Upvotes: 1