'Get the currently signed-in user with AngularFire or Angular and Firebase Auth?
The Firebase Auth docs explain how to get the currently signed-in user, in other words, to get the signed-in user's name, photo, etc. I can't get the provided code to run in Angular. Here's the provided code:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
Let's translate that into Angular.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat/app';
import { getAuth, onAuthStateChanged } from "firebase/auth";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent {
constructor(
private router: Router,
public auth: getAuth,
) { }
onAuthStateChanged(this.auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
}
That is a mess and just crashes. Should I make an Observable?
Solution 1:[1]
I figured it out. Sometimes just writing out a question and then taking a break makes the answer become clear.
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat/app';
import { getAuth, onAuthStateChanged } from "firebase/auth";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
auth = getAuth();
constructor(
private router: Router,
public auth: AngularFireAuth,
) { }
ngOnInit(): void {
onAuthStateChanged(this.auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
console.log(user.uid);
console.log(user.displayName);
// ...
} else {
// User is signed out
// ...
}
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
