Angular 2 AuthGuard + Firebase Auth

前端 未结 2 1944
暖寄归人
暖寄归人 2020-12-13 15:02

I\'m trying to build an AuthGuard for Angular 2 routes using Firebase Auth.

This is the AuthGuard Service:

import { Injectable }             from \'@         


        
相关标签:
2条回答
  • 2020-12-13 15:50

    Complete the observable using .take(1) to make the component render.

    import {Observable} from "rxjs/Observable";
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/take';
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return this.af.auth.map((auth) => {
            if (!auth) {
              this.router.navigateByUrl('login');
              return false;
            }
            return true;
        }).take(1);
      }
    
    0 讨论(0)
  • 2020-12-13 16:01

    For newer versions of AngularFire, you have to use authState instead:

    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(
        private afAuth: AngularFireAuth,
        private router: Router
      ) {}
    
      canActivate(): Observable<boolean> {
        return this.afAuth.authState
          .take(1)
          .map(authState => !!authState)
          .do(auth => !auth ? this.router.navigate(['/login']) : true);
      }
    }
    

    Don't forget to import take, map and do from rxjs/add/operator.

    0 讨论(0)
提交回复
热议问题