首页 > 解决方案 > 刷新页面以角度 5 自动注销

问题描述

我正在使用 firebase 进行登录和注册。那是我的 authService 的样子:

token: string;
authenticated: boolean = false;
signinUser(email: string, password: string) {
        firebase
            .auth()
            .signInWithEmailAndPassword(email, password)
            .then(response => {
                this.authenticated = true;
                console.log('authService-->signinUser-->authenticated', this.authenticated);


                //Set the a wallet using a combination of the email and the name of the network e.g. Majd@gmail.com@stschain
                this.dataService.setWallet(`${email}${this.domainExtenstion}`);
                this.setEmail(email);
                this.router.navigate(['/dashboard']);
                console.log('sinign in')
                firebase
                    .auth()
                    .currentUser.getIdToken()
                    .then(
                        (token: string) => {
                            (this.token = token);
                            // localStorage.setItem('token', JSON.stringify(token));
                        }
                    );
            })
            .catch(error => {
                console.log(error);
                alert(error);
            });

    }

isAuthenticated() {
   return this.token != null;       
}

并在我的 authGuardService 中调用 canactivate 方法,如下所示:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (!this.authService.authenticated) {
      console.log('cant load' )
      this.router.navigate(['/signin']);
    }
    console.log('can load' )
    return this.authService.isAuthenticated();
  }
}

但是当我刷新页面时,这个authenticated值总是假的。

请任何人都知道会感激的原因。

标签: angularfirebase-authenticationangular5auth-guard

解决方案


在您的代码中,您可以:

firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then(response => {
        this.authenticated = true;

then块仅在用户显式登录时运行。它不会在页面重新加载时自动运行。

但是当页面重新加载时,Firebase 身份验证自动(尝试)恢复用户的登录会话,您的代码只是不知道它。要检测身份验证状态更改,请使用身份验证状态侦听器(如文档中所示):

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

请注意,onAuthStateChanged显式(例如您调用signInWith...)和隐式(例如页面重新加载)身份验证状态更改都会调用回调,因此请考虑将(部分)代码从then()块移动到此回调。


推荐阅读