AuthGuard doesn't wait for authentication to finish before checking user

后端 未结 2 875
清酒与你
清酒与你 2020-12-10 02:22

I\'ve read the guide here: https://angular.io/docs/ts/latest/guide/router.html

Seems pretty straightforward, however, I\'m not sure how to use angularfire2\'s authen

相关标签:
2条回答
  • 2020-12-10 02:36

    It may be different in some versions of the router but I needed to return an observable that completes.

    import { CanActivate, Router } from '@angular/router'
    
    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private af: AngularFire, private router: Router) { }
    
      canActivate(): Observable<boolean> {
        return this.af.auth.map(user => {
          if (user != null)
            return true
          this.router.navigate(['/login'])
        })
        .take(1) // To make the observable complete after the first emission
      }
    }
    
    0 讨论(0)
  • 2020-12-10 02:53

    The problem is with your code. In the AuthGuard you check the result of authenticated() method that will most probably return false as the user property is still not set. Try this:

    AuthService:

    import { Injectable } from '@angular/core';
    import { AngularFire } from 'angularfire2';';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class AuthService {
    
      private user: any;
    
      constructor(private af: AngularFire) { }
      setUser(user) { this.user = user; }
      getAuthenticated(): Observable<any> { return this.af.auth; }
    }
    

    AuthGuard:

    @Injectable()
    export class AuthGuard implements CanActivate {
    
      constructor(private router: Router, private authService: AuthService) { }
    
      canActivate(): Observable<boolean> | boolean {
        // here check if this is first time call. If not return 
        // simple boolean based on user object from authService
        // otherwise:
    
        return this.authService.getAuthenticated.map(user => {
              this.authService.setUser(user);
              return user ? true : false;
        })
    
      } 
    }
    
    0 讨论(0)
提交回复
热议问题