Refresh page get log out automatically in angular 5

雨燕双飞 提交于 2019-12-25 18:42:07

问题


I'm using firebase for the signIn and signup. that is my authService look like :

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;       
}

and in my authGuardService im calling canactivate methode like this :

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();
  }
}

but when i refresh the page this authenticated value get false always.

Please, anyone, know the cause that will appreciate.


回答1:


In your code you do:

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

This then block only runs when the user explicitly signs in. It does not automatically run when the page gets reloaded.

But Firebase Authentication does automatically (try to) restore the user's sign-in session when the page is reloaded, your code just isn't aware of it. To detect auth state changes, use an auth state listener (as shown in the documentation):

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

Note that the onAuthStateChanged callback gets called for both explicit (e.g. you calling signInWith...) and implicit (e.g. page reload) auth state changes, so consider moving (some of) your code from the then() block to this callback.



来源:https://stackoverflow.com/questions/54417286/refresh-page-get-log-out-automatically-in-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!