Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Last active August 28, 2020 02:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save codediodeio/3e28887e5d1ab50755a32c1540cfd121 to your computer and use it in GitHub Desktop.
Save codediodeio/3e28887e5d1ab50755a32c1540cfd121 to your computer and use it in GitHub Desktop.
Angular Firebase Router Guard with Browser Refresh
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']);
}
})
}
}
@Mrgove10
Copy link

Mrgove10 commented Jan 2, 2020

error TS2339: Property 'take' does not exist on type 'Observable'

@Crypt0Graphic
Copy link

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']);
        }
      })
    );
  }

@KheireddineAzzez
Copy link

10x men <3

@ljchuello
Copy link

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