Angularfire2读取数据一次

标签 angular firebase firebase-realtime-database angularfire2

每当用户登录时,我都会运行此命令将其数据保存在我的 users 节点中。不幸的是,每当用户注销时,我都会收到此错误:

FIREBASE WARNING: Exception was thrown by user callback. Error: permission_denied at /users/userID: Client doesn't have permission to access the desired data.
    at Error (native)
    at G (http://localhost:4200/main.bundle.js:75367:36)
    at Object.G (http://localhost:4200/main.bundle.js:75371:86)
    at yh (http://localhost:4200/main.bundle.js:75356:98)
    at nh.h.wd (http://localhost:4200/main.bundle.js:75349:310)
    at af.wd (http://localhost:4200/main.bundle.js:75252:364)
    at vd.hg (http://localhost:4200/main.bundle.js:75250:280)
    at yd (http://localhost:4200/main.bundle.js:75203:464)
    at WebSocket.La.onmessage (http://localhost:4200/main.bundle.js:75202:245)
    at WebSocket.wrapFn [as _onmessage] (http://localhost:4200/main.bundle.js:94097:29) 

这意味着 Firebase 会继续监听我的用户,直到页面重定向。所以我只需要尝试运行一次。有什么想法吗?

在用户面板中,我有以下代码:

ngOnInit() {
        this.authService.loadUser().subscribe(() => {
            this.user = this.authService.userData;
        });
  }

这是指我的 loadUser() 方法从 firebase 获取数据(我只是尝试放置 take(1) 但仍然收到此权限错误):

loadUser() {
      return this.af.database.object('/users/'+this.uid).take(1).map(user => {
            this.userData = user;
        });
  }

在我的注销中,我只需执行以下操作:

logout() {
      this.auth.logout();
      this.userData = null;
    this.isLoggedIn = false;
    this.router.navigate(['']);
  }

我认为发生错误的原因是,即使在 this.auth.logout(); 之后,Firebase 仍保持与我的用户的连接,并且在路由器导航之前,他一直尝试刷新数据。这就是为什么我只需要执行此操作一次。

最佳答案

我以前也遇到过这个问题。这是因为有迹象表明,注销后立即发生了数据同步调用。我的解决方案是在注销例程期间使用 goOffline() 断开与 Firebase 的连接,并且它将阻止立即通过 Websocket 进行任何进一步的数据同步。

logout () {
  firebase.database().goOffline();
  // other log out code
}

重要提示:如果您在注销时调用 goOffline(),则您必须调用 goOnline(),如果您打算再次登录。我建议您每次登录时都调用 goOnline()

关于Angularfire2读取数据一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40105221/

相关文章:

javascript - 如何根据 <select> 的值动态生成 X 数量的新 &lt;input&gt; (在 Angular2 中)?

javascript - Firebase Firestore 获取用户相关数据

javascript - 如何在 Firebase 中手动取消 Once() ?

Angular 10 : Property 'comments' does not exist on type 'typeof Dish'

javascript - 通过@Input()传递的数据

firebase - 从 firebase 获取数据给出 null 但热重载后工作正常

android - Firebase 查看 friend 的帖子

node.js - firebase实时数据库中的自动增量Id生成器

angular - ngrx/store 未显示表单的更新值

Firebase:无法验证 Namecheap 域的所有权