Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular Firebase Router Guard with Browser Refresh
import { Injectable } from '@angular/core';
import { Auth, authState } from '@angular/fire/auth';
import { CanActivate, Router, UrlTree } from '@angular/router';
import { map, Observable, take, tap } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: Auth, private router: Router) { }
canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return authState(this.auth).pipe(
take(1),
map(user => !!user),
tap(loggedIn => {
if (!loggedIn) {
return this.router.navigate(['/auth/login']);
}
return true;
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment