离子存储不会更新值

时间:2019-04-28 22:07:42

标签: firebase ionic4 ionic-storage

使用Firebase成功登录我的应用程序后,我想存储一堆信息(例如用户电子邮件,用户uid,用户名...),并在整个应用程序中使用它。我为此找到的最好方法是使用离子存储。

现在,在第一次登录时可以正常工作,但是如果我注销并以其他用户身份登录,则仍会显示第一个用户信息,而不是新用户信息。请注意,当用户点击注销时,我正在清理我的所有存储。我的代码:

身份验证(防护)::登录后我正在再次检查用户身份验证状态。

return this.AFauth.authState.pipe(map(auth => {
  if (auth !== null && auth !== undefined) {
    this.saveUserInStorage(auth);
    return true;
  } else {
    this.router.navigate(['/home']);
    return false;
  }
}))

在存储中保存Firebase信息

saveUserInStorage(auth) {
  this.storage.ready().then(() => {
    this.storage.clear(); //cleaning again just in case...
    this.storage.set('user_uid', auth.uid);
    this.storage.set('user_name', auth.displayName);
    this.storage.set('user_email', auth.email);
    this.storage.set('user_photoUrl', auth.photoUrl);
  }).catch(err => {
    console.log('no pudimos guardar');
  });
}

注销功能

logOutUser() {
  firebase.auth().signOut().then(result => {
    // after user hits logout, I erase my storage
    this.storage.remove('user_email');
    this.storage.clear();
    this.router.navigate(['/home']);
  }).catch(error => {
    console.log(error);
    // An error happened.
  });
}

我必须重新加载我的网页才能看到最后一个登录的用户。

1 个答案:

答案 0 :(得分:0)

这可能与存储没有任何关系,但是您必须重置显示信息的表单或字段,或者更改信息的加载方式。我建议两个选项

  1. 在页面上使用ionViewWillEnter并将代码放在其中的信息从存储中拉出。 (这可能是最简单的)

  2. 使用BehaviorSubjects总是在更改信息时发出新事件,并侦听使用该信息的事件。

这样做的原因是,每个页面一旦创建就不会再次创建自己。如果您在ngOnInit中进行控制台登录,则可以看到此信息。因此,您的旧信息会保留在该页面上,直到您找到另一种更新方式。 (使用ionViewWillEnter或Observables)