Angular 2 AuthGuard + Firebase Auth

前端 未结 2 1954
暖寄归人
暖寄归人 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条回答
  •  萌比男神i
    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 {
        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.

提交回复
热议问题