【问题标题】:Angularfire2 read data onceAngularfire2 读取数据一次
【发布时间】:2016-11-30 17:23:39
【问题描述】:

每当用户登录时,我都会运行它以将他的数据保存在我的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 仍保持与我的用户的连接,并且在路由器导航之前,他一直在尝试刷新数据。这就是为什么我只需要执行一次此操作。

【问题讨论】:

    标签: angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      我也遇到了同样的问题。我对 Observables 比较陌生,所以如果我的解释不完全正确,我深表歉意。

      我认为问题在于您订阅了 AngularFire 的 object() 函数返回的 FirebaseObjectObservable,因此即使您注销,数据仍会尝试保持同步。

      我的解决方案是在注销之前取消订阅,因此您的 logout 函数将如下所示:

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

      希望仍然有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-13
        • 1970-01-01
        • 2017-10-10
        • 1970-01-01
        • 1970-01-01
        • 2013-12-01
        • 2018-03-29
        相关资源
        最近更新 更多