【问题标题】:Refs not rerunning after onAuthStateChanged changes Firebase 3.0.0onAuthStateChanged 更改 Firebase 3.0.0 后,Refs 不会重新运行
【发布时间】:2016-09-19 02:56:04
【问题描述】:

以下代码在users/ 路径上附加了一个观察程序,并在值更改时记录用户。

在 firebase 上,这个 users/ 树会根据当前经过身份验证的用户的访问权限进行门控。

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

firebase.database().ref('users').on('value', function(snapshot) {
  // log the users
  console.log(snapshot.val())
});

问题是在使用具有正确权限的用户登录后,users/ 树没有被记录,如上述回调所示。

除了在onAuthStateChanged 的回调中移动users/ 观察者之外,还有其他解决方案吗?那是内存泄漏的味道。

【问题讨论】:

  • 我将在下面写一个有根据的猜测。但如果没有看到您的安全规则,它仍然只是:一个有根据的猜测。

标签: javascript firebase firebase-realtime-database firebase-authentication


【解决方案1】:

当您将侦听器附加到节点时,Firebase 数据库会立即评估当前连接是否有权从该节点读取。如果没有,它会取消监听器。

由于您在未经身份验证的情况下开始,因此会立即取消侦听器。如果您还将错误回调传递给on(),您可以轻松看到这一点:

firebase.database().ref('users').on('value', function(snapshot) {
  console.log(snapshot.val())
}, function(error) {
  console.error(error);
});

要解决这个问题,您需要在用户通过身份验证后附加监听器:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    firebase.database().ref('users').on('value', function(snapshot) {
      console.log(snapshot.val())
    }, function(error) {
      console.error(error);
    });
  } else {
    // No user is signed in.
    ... do other stuff
  }
});

【讨论】:

  • 如何确保在用户注销或重新连接后清理这些 ref?
  • 你解决了吗?我的应用中有很多 .on 监听器,我想取消所有监听器。
猜你喜欢
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多