Created
July 21, 2016 10:32
-
-
Save Zyzle/7fcdf92b23bd1ba1efad2e3418cd71bf to your computer and use it in GitHub Desktop.
Angular 2 Firebase auth guard
This file contains hidden or 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, Router } from '@angular/router'; | |
import { FirebaseAuth, FirebaseAuthState } from 'angularfire2'; | |
import { Observable } from 'rxjs/Observable'; | |
@Injectable() | |
export class AuthGuard implements CanActivate { | |
constructor(private auth: FirebaseAuth, private router: Router) { } | |
canActivate(): Observable<boolean> { | |
return this.auth.take(1) | |
.map((authState: FirebaseAuthState) => !!authState) | |
.do(authenticated => { | |
if (!authenticated) { | |
this.router.navigate(['/login']); | |
} | |
}); | |
} | |
} |
Or for RXJS 6+
return this.auth.authState.pipe(
take(1),
map(authState => !!authState),
tap(auth => !auth ? this.router.navigateByUrl('/login') : true)
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it doesn't work
here is the work code
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/do';
@Injectable()
export class AuthGuard implements CanActivate {