Angular 2 - Route guard not working on browser refresh

我是研究僧i 提交于 2019-12-01 10:43:53

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;
    });


}
madHorse

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' ]);
      })
    }

}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!