onAuthStateChanged更改Firebase 3.0.0后,不会重新运行 [英] Refs not rerunning after onAuthStateChanged changes Firebase 3.0.0

查看:126
本文介绍了onAuthStateChanged更改Firebase 3.0.0后,不会重新运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在firebase上,这个用户/ 树根据当前认证用户的访问权限进行门控。

pre $ firebase.auth()。 //用户已经登录
...做其他的东西
} else {
//没有用户登录
...做其他的东西
}
}); ('value',function(snapshot){
//记录用户
console.log(快照)
$ b firebase.database()。ref .val())
});

问题出在用正确权限的用户登录之后,用户/ 树没有被记录,如上面的回调中所示。

除了在的回调中移动 users / 观察者外,还有其他解决方案吗?onAuthStateChanged 。内存泄漏的味道。当您将侦听器附加到节点时,Firebase数据库会立即评估当前连接是否有权从该节点读取数据。如果没有,它将取消侦听器。



由于您未经身份验证,侦听器会立即被取消。 ():

 <$ ('value',function(snapshot){
console.log(snapshot.val())
},函数(code> firebase.database错误){
console.error(error);
});

为了解决这个问题,您需要在用户之后添加监听器已经被认证:

$ p $ firebase.auth()。onAuthStateChanged(function(user){
if(user){ ('value',function(snapshot){
console.log(snapshot.val())
},函数(
firebase.database()。ref错误){
console.error(error);
});
} else {
//没有用户登录
...做其他的事
}
});


The following code below attaches a watcher on the users/ path and logs the users when the value changes.

On firebase, this users/ tree is gated depending on the current authenticated users' access permissions.

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())
});

The issue is after logging in with a user with correct permissions, the users/ tree doesn't get logged as shown in the above callback.

Is there other solutions other than moving the users/ observer inside the callback of onAuthStateChanged. That smells of memory leaks.

解决方案

When you attach a listeners to a node, the Firebase Database immediately evaluates whether the current connection has permission to read from that node. If it doesn't, it cancels the listener.

Since you start out unauthenticated, the listener is immediately cancelled. You can easily see this if you also pass an error callback into on():

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

To solve this problem, you need to attach the listener after the user has been authenticated:

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
  }
});

这篇关于onAuthStateChanged更改Firebase 3.0.0后,不会重新运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆