用户在使用Firebase作为后端重新加载页面时注销

mspsb9vt  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(106)

我已经为我的Angular 2应用程序构建了身份验证。我已经通过使用Firebase身份验证服务实现了这一点。在重新加载页面时,用户注销,但令牌仍然存在于localStorage中。
这是我的代码:

export class AdminService {

email;
password;
error;
invalidLogin;
isLoggedIn = false;

    constructor(private af: AngularFireAuth,private router: Router,private route: ActivatedRoute) {
     }

      login(){
        this.af.auth.signInWithEmailAndPassword(this.email,this.password)
        .then(authState => {
          if(authState){
            let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl');
            this.router.navigate([returnUrl||'/']);
            this.isLoggedIn = true;
          }
          else this.invalidLogin = true;
        })
      }

      logout(){   

        this.af.auth.signOut();
        this.isLoggedIn = false;
        this.router.navigate(['/'])
      }

    }
ikfrs5lh

ikfrs5lh1#

用户实际上不会注销。当您重新加载页面时,Firebase客户端将检测本地存储中的信息并再次登录用户。您的代码无法检测到这一点,因此无法正确地路由用户。
在常规的Firebase JavaScript客户端中,您可以通过监听onAuthStateChanged()事件来解决这个问题:

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

在AngularFire2中,有一个FirebaseIdTokenObservable,它暴露了一个Observable<firebase.User>。它似乎也是这么做的,虽然我承认我从来没有用过它。

kiayqfof

kiayqfof2#

如果你想使用async函数,你也可以这样做

public async getCurrentUser(): Promise<User | null> {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged(user => {
        resolve(user);
      });
    });
  }

现在你可以用在警卫身上了

相关问题