Angular 2 - Route guard not working on browser refresh

前端 未结 3 2064
被撕碎了的回忆
被撕碎了的回忆 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: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 {
          return Observable.from(this.auth)
            .take(1)
            .map(state => !!state)
            .do(authenticated => {
          if 
            (!authenticated) this.router.navigate([ '/login' ]);
          })
        }
    
    }
    

提交回复
热议问题