Having these routes defined in app.module.ts
...
{ path: \'mypath\', component: MyComponent, canActivate: [RouteGuard] },
{ path: \'\', redirectTo: \'/home\
You're making an asynchronous call to your auth service, that means canActivate()
returns this.loggedIn
before it sets its value to true or false. And since the guard is called every time you take the 'mypath' route this.isLoggedin
will be reset to null
Now to avoid this behavior you can use a boolean outside of your guard and use that boolean to keep track of if you're logged in or not.
you can an asynchronous result to the route guard :
canActivate(): Promise<boolean> {
let self = this;
return this.auth.toPromise().then(auth => {
if (auth) { self.loggedIn = true; }
else { self.loggedIn = false; }
self.router.navigate(['/login']); for future implememtation
return self.loggedIn;
});
}
Thanks to the suggestion of @Bougarfaoui El houcine and YounesM here is my new guard service (fully taken from this post: Create a Full Angular Authentication System with Firebase
It works perfectly and solve my problem.
import { CanActivate, Router } from '@angular/router';
import { AngularFireAuth } from "angularfire2/angularfire2";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Rx";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
@Injectable()
export class RouteGuard implements CanActivate {
constructor(private auth: AngularFireAuth, private router: Router) {}
canActivate(): Observable<boolean> {
return Observable.from(this.auth)
.take(1)
.map(state => !!state)
.do(authenticated => {
if
(!authenticated) this.router.navigate([ '/login' ]);
})
}
}