Attempting to create an AuthGuard for Angular 2 routes with Firebase Auth integration.
This is the implementation of the AuthGuard Service:
import { Injectable } from '@angular/core';
import { CanActivate, Router,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private AuthService: AuthService,
private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.AuthService.loggedIn) { return true; }
this.router.navigate(['login']);
return false;
}
}
Here is the AuthService that verifies if a user is logged in and updates the 'loggedIn' property accordingly.
import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Router } from '@angular/router';
@Injectable()
export class AuthService {
loggedIn: boolean = false;
constructor(
public af: AngularFire,
public router: Router) {
af.auth.subscribe(user => {
if(user){
this.loggedIn = true;
}
});
}
}
The main issue lies in the asynchrony problem. The canActivate() method in AuthGuard always returns false because the subscription does not update 'loggedIn' in time.
What is the recommended solution to address this?
UPDATE:
Modified the AuthGuard to return an observable.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.af.auth.map((auth) => {
if (!auth) {
this.router.navigateByUrl('login');
return false;
}
return true;
});
}
Although it prevents redirection to the login page, the AuthGuarded component fails to render.
Uncertain whether the issue stems from my app.routes configuration. Here is the corresponding code snippet:
const routes: Routes = [
{ path: '', component: MainComponent, canActivate: [AuthGuard] },
...
];
export const routing = RouterModule.forRoot(routes);