Skip to content

Instantly share code, notes, and snippets.

@adagala
Created September 25, 2021 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adagala/899b7f77ae397e5c9262015ca39166b1 to your computer and use it in GitHub Desktop.
Save adagala/899b7f77ae397e5c9262015ca39166b1 to your computer and use it in GitHub Desktop.
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