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 { 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']);
}
})
}
}
@amiroffme-zz

This comment has been minimized.

Copy link

@amiroffme-zz amiroffme-zz commented Aug 2, 2018

Thanks for this 👍

@Mrgove10

This comment has been minimized.

Copy link

@Mrgove10 Mrgove10 commented Jan 2, 2020

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

@Crypt0Graphic

This comment has been minimized.

Copy link

@Crypt0Graphic Crypt0Graphic commented Jan 18, 2020

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

This comment has been minimized.

Copy link

@KheireddineAzzez KheireddineAzzez commented May 16, 2020

10x men <3

@ljchuello

This comment has been minimized.

Copy link

@ljchuello ljchuello commented Aug 28, 2020

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