Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Firebase-在localStorage对象有效时保持用户登录_Javascript_Angular_Typescript_Firebase_Firebase Authentication - Fatal编程技术网

Javascript Firebase-在localStorage对象有效时保持用户登录

Javascript Firebase-在localStorage对象有效时保持用户登录,javascript,angular,typescript,firebase,firebase-authentication,Javascript,Angular,Typescript,Firebase,Firebase Authentication,我有一个应用程序,我正在与离子,Angular2和Firebase建设 我目前正在做的是,当用户登录或注册时,他们的auth.currentUser信息将保存在localStorage中。我的代码当前假定,如果用户在localStorage中设置了user变量,则该用户也已登录。然而,我才意识到事实并非如此 我的localStorage变量user如下所示: ngOnInit() { Promise.all([ //data storage get all.. this.storag

我有一个应用程序,我正在与离子,Angular2和Firebase建设

我目前正在做的是,当用户登录或注册时,他们的
auth.currentUser
信息将保存在
localStorage
中。我的代码当前假定,如果用户在
localStorage
中设置了
user
变量,则该用户也已登录。然而,我才意识到事实并非如此

我的
localStorage
变量
user
如下所示:

ngOnInit() {
  Promise.all([ //data storage get all..
    this.storage.get('user')
  ])
  .then(([user]) => {
    this.userData = user; //set the user storage to this.userData
    console.log(this.userData)
  })
  .catch(error => {
    console.log("Storage Error.");
  });
}

我是这样理解的:

ngOnInit() {
  Promise.all([ //data storage get all..
    this.storage.get('user')
  ])
  .then(([user]) => {
    this.userData = user; //set the user storage to this.userData
    console.log(this.userData)
  })
  .catch(error => {
    console.log("Storage Error.");
  });
}
所以我有所有的用户信息,除了他们没有实际登录。。。因此,当我这样做时:

this.afAuth.auth.onAuthStateChanged((user) => {
  if (user) {
    console.log(user)
  } else {
    console.log("Not logged in")
  }
});
它显示用户未登录。当我有本地存储信息时,是否可以让用户保持登录状态

或者可能只是让登录状态始终登录,除非用户注销?它永远不会过期吗


现在我该怎么办?任何建议都很好!谢谢。

Firebase Manager用户使用不同的方式。您不应该依赖localstorage来检测用户是否记录了它。您应该依靠firebase来检查用户是否已登录。因为firebase是基于web套接字构建的,所以它应该非常快。因此,让我们按照以下方式重写
ngOnInit

ngOnInit() {
    const user = this.afAuth.auth.currentUser;

    if (user) {
      this.userData = user;
    } else {
      // force them to reauthenticate
      user.reauthenticateWithCredential(credential)
        .then(function() {
          // User re-authenticated.
          this.userData = this.afAuth.auth.currentUser;
        }).catch(function(error) {
         // An error happened.
        });
    }
}

在此处阅读有关在Firebase中管理用户的更多信息:。希望这有帮助。

正如Vijai所说,只需从Firebase auth中检查用户对象即可。如果用户不为null,则有人登录。您仍然可以将内容保存在本地存储中,但无需保存用户对象,因为它已经存在于某个已登录的应用程序中。