在 onAuthStateChanged 更改 Firebase 3.0.0 后,引用不会重新运行

Refs not rerunning after onAuthStateChanged changes Firebase 3.0.0

下面的代码在 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/ 观察者之外,还有其他解决方案吗?那闻起来有内存泄漏的味道。

当您将侦听器附加到节点时,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
  }
});