Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular 2 Firebase auth guard
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']);
}
});
}
}
@vstymkovskyi

This comment has been minimized.

Copy link

@vstymkovskyi vstymkovskyi commented Jul 13, 2017

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 {

constructor(
    private router: Router,
    private auth: AngularFireAuth
) { }

canActivate(): Observable<boolean> {
    return this.auth.authState
        .take(1)
        .map(authState => !!authState)
        .do(auth => !auth ? this.router.navigate(['/login']) : true);
}
@markbell2410

This comment has been minimized.

Copy link

@markbell2410 markbell2410 commented Feb 26, 2019

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
You can’t perform that action at this time.