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

编程入门 行业动态 更新时间:2024-10-22 13:45:37
本文介绍了onAuthStateChanged更改Firebase 3.0.0后,不会重新运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

在firebase上,这个用户/ 树根据当前认证用户的访问权限进行门控。 pre $ firebase.auth()。 //用户已经登录 ...做其他的东西} else { //没有用户登录 ...做其他的东西 } }); ('value',function(snapshot){ //记录用户 console.log(快照) $ b firebase.database()。ref .val())});

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

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

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

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后,不会重新运行

本文发布于:2023-11-14 04:33:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586229.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:onAuthStateChanged   Firebase

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!