I've read the guide here: https://angular.io/docs/ts/latest/guide/router.html
Seems pretty straightforward, however, I'm not sure how to use angularfire2's authentication within an auth guard (canActivate
). What I've tried is:
AuthService
import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';
@Injectable()
export class AuthService {
private user: any;
constructor(private af: AngularFire) {
this.af.auth.subscribe(user => {
this.user = user;
})
}
get authenticated(): boolean {
return this.user ? true : false;
}
}
AuthGuard
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) { }
canActivate(): Observable<boolean> | boolean {
if (this.authService.authenticated)
return true;
this.router.navigate(['/login']);
return false;
}
}
I've also added AuthService to bootstrap providers.
This sort of works fine, however, my main problem is when I refresh (or initially load) the page on that has AuthGuard
it always redirects me to the login page since the AuthGuard
doesn't wait for the authentication response. Is there a way to wait for the authentication to finish (even if it's failed) and then check whether the user is authenticated?