Last active
August 28, 2020 02:50
-
-
Save codediodeio/3e28887e5d1ab50755a32c1540cfd121 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 { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; | |
import { Observable } from 'rxjs/Observable'; | |
import { AngularFireAuth } from 'angularfire2/auth'; | |
import 'rxjs/add/operator/do'; | |
import 'rxjs/add/operator/map'; | |
import 'rxjs/add/operator/take'; | |
@Injectable() | |
export class AuthGuard implements CanActivate { | |
constructor(private afAuth: AngularFireAuth, private router: Router) {} | |
canActivate( | |
next: ActivatedRouteSnapshot, | |
state: RouterStateSnapshot): Observable<boolean> { | |
return this.afAuth.authState | |
.take(1) | |
.map(user => !!user) | |
.do(loggedIn => { | |
if (!loggedIn) { | |
console.log("access denied") | |
this.router.navigate(['/login']); | |
} | |
}) | |
} | |
} |
error TS2339: Property 'take' does not exist on type 'Observable'
error TS2339: Property 'take' does not exist on type 'Observable'
import { take, map, tap } from 'rxjs/operators';
And use this updated code:
canActivate(): Observable<boolean> {
return this.afAuth.authState.pipe(
take(1),
map(user => !!user),
tap(loggedIn => {
if (!loggedIn) {
console.log('Access Denied');
this.router.navigate(['/login']);
}
})
);
}
10x men <3
error TS2339: la propiedad 'toma' no existe en el tipo 'Observable'
importar {tomar, mapa, tocar} de 'rxjs / operadores';
Y usa este código actualizado:
canActivate(): Observable<boolean> { return this.afAuth.authState.pipe( take(1), map(user => !!user), tap(loggedIn => { if (!loggedIn) { console.log('Access Denied'); this.router.navigate(['/login']); } }) ); }
It works thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this 👍