Skip to content

Instantly share code, notes, and snippets.

@StefanNieuwenhuis
Created April 3, 2017 05:15
Show Gist options
  • Save StefanNieuwenhuis/2441386d5e2084d74aa4755bf109a18a to your computer and use it in GitHub Desktop.
Save StefanNieuwenhuis/2441386d5e2084d74aa4755bf109a18a to your computer and use it in GitHub Desktop.
AngularFireAuthGuard
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AngularFire } from 'angularfire2';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private af: AngularFire, private router:Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> {
return this.af.auth.map(auth => {
if (auth !== null){
return true;
}
this.router.navigate(['/login'])
});
};
}
@beeman
Copy link

beeman commented Jan 11, 2018

It can even be (a bit) simpler:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AngularFire } from 'angularfire2';

import 'rxjs/add/operator/map';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private af: AngularFire, private router:Router) {}

  canActivate(): Observable<boolean> {
    return this.af.auth.map(auth => {
      if (auth !== null){
        return true;
      }
      this.router.navigate(['/login'])
    });
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment