Created
September 25, 2021 15:45
-
-
Save adagala/899b7f77ae397e5c9262015ca39166b1 to your computer and use it in GitHub Desktop.
Angular Firebase Router Guard with Browser Refresh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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