使用服务来检查用户是否已通过身份验证,但防护功能无法正常工作

时间:2018-09-12 15:12:57

标签: angular firebase firebase-authentication

我实现了Firebase身份验证页面。因此,我像这样设置了一个角度service UserService

export class UserService {

  public authenticated: boolean;
  public error: any;
  public currentUser: User;

  constructor(public afAuth: AngularFireAuth) {
    this.authenticated = false;
    this.afAuth.authState.subscribe(authenticated => {
      if (authenticated) {
        this.authenticated = true;
      }
    });
  }

  async loginWithGoogle() {
    try {
      const result = await this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
      this.authenticated = true;
      console.log(result.user);
    } catch (e) {
      this.error = e;
    }
  }

  async loginWithFacebook() {
    try {
      await this.afAuth.auth.signInWithPopup(new auth.FacebookAuthProvider());
      this.authenticated = true;
    } catch (e) {
      this.error = e;
    }
  }

}

这似乎正常。但是,当我尝试访问受以下防护措施保护的路由时:

export class AuthenticatedGuard implements CanActivate {
  constructor(public userService: UserService, private router: Router) { }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    alert(this.userService.authenticated);
    if (this.userService.authenticated) {
      return true;
    }
    this.router.navigate(['/']);
    return false;
  }
}

但是this.userService.authenticated始终是false

有更好的方法吗?如果没有,这是怎么了?也许authenticated应该是守卫订阅的Observable

1 个答案:

答案 0 :(得分:0)

我希望方法获得authenticated()而不是使用布尔属性。您的布尔属性将始终具有相同的值。尝试添加以下方法:

get authenticated(){
  if(this.afAuth.auth.currentUser) {
  this.currentUser = this.afAuth.auth.currentUser
  return true;
  }
  else {
    return false
  };    
}

,然后使用this.userService.authenticated()代替this.userService.authenticated

编辑

我还将您的 UserService 的构造函数更改为:

constructor(public afAuth: AngularFireAuth) {
    this.authenticated = this.authenticated()
  }

您必须记住,您需要使用功能authenticated()而不是经过验证的布尔值。这是因为尽管类是单例的,但变量的更改不会自动通知不同的组件。