I\'m trying to build an AuthGuard for Angular 2 routes using Firebase Auth.
This is the AuthGuard Service:
import { Injectable } from \'@
Complete the observable using .take(1) to make the component render.
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.af.auth.map((auth) => {
if (!auth) {
this.router.navigateByUrl('login');
return false;
}
return true;
}).take(1);
}
For newer versions of AngularFire
, you have to use authState
instead:
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private afAuth: AngularFireAuth,
private router: Router
) {}
canActivate(): Observable<boolean> {
return this.afAuth.authState
.take(1)
.map(authState => !!authState)
.do(auth => !auth ? this.router.navigate(['/login']) : true);
}
}
Don't forget to import take
, map
and do
from rxjs/add/operator
.