Angular 2 - Route guard not working on browser refresh

前端 未结 3 2069
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 01:12

Having these routes defined in app.module.ts

...
{ path: \'mypath\', component: MyComponent, canActivate: [RouteGuard] }, 
{ path: \'\', redirectTo: \'/home\         


        
相关标签:
3条回答
  • 2021-01-15 01:16

    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.

    0 讨论(0)
  • 2021-01-15 01:37

    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;
        });
    
    
    }
    
    0 讨论(0)
  • 2021-01-15 01:42

    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' ]);
          })
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题