【问题标题】:How to continuously listen to changes in firebase and stop when user logout如何在用户注销时持续监听firebase的变化并停止
【发布时间】:2017-12-24 14:17:43
【问题描述】:

我的实际是“NgFor 只支持绑定到 Iterables,比如 Arrays " 并且由于之前也有人问过,所以我改变了问题。而且我无法在我的代码上下文中理解它的正确实现:

我之前的代码是这样的:

this.afdb.list('/all-users/' + this.userid + '/all-notifications/',
    ref => ref.orderByChild('status').equalTo('pending')).
    valueChanges().subscribe( (data) => {
        this.userAllNotifications = data;
        data.forEach( (item: any) => {
            if (item.status === 'pending') {
                // some code....
            } 
        });
    });

但我不知道如何在这段代码中使用“ref.off()”。在阅读了一些文档后,我决定实现它,如下所示:

const refNotify = firebase.database().ref('/all-users/' + this.userid + '/all-notifications/')
                                        .orderByChild('status').equalTo('pending');
    if (firebase.auth().currentUser) {
         refNotify.on('value', (snapshot) => {
            this.userAllNotifications = snapshot.val();
        });
    } else {
        refNotify.off();
    }

它会抛出错误“NgFor 仅支持绑定到 Iterables,例如 Arrays " 代表 "this.userAllNotifications"。

我试着改成这样:

if (firebase.auth().currentUser) {
         refNotify.on('value', (snapshot) => {
            this.userAllNotifications = [];
            snapshot.forEach((childSnapshot) => {
              this.userAllNotifications.push(childSnapshot.val());
            });
        });
    } else {
        refNotify.off();
    }

但随后它显示“childSnapshot”的以下错误 -

Argument of type '(childSnapshot: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean'. Type 'void' is not assignable to type 'boolean'.

我无法弄清楚如何正确实施它,但是 尝试实现的代码可以:

  1. 持续收听新通知
  2. 并在用户注销时关闭 ref 侦听器。

在 html 中,我的代码是这样的:

<li *ngFor="let notify of userAllNotifications" (click)="notifiesViewed(notify)">

【问题讨论】:

    标签: javascript angular firebase-realtime-database


    【解决方案1】:

    所以,我想出了这个解决方案:

    this.userAllNotifications = this.notifyService.getUserNotications(this.userid);
        this.subscriptionNotifies = this.userAllNotifications.subscribe( (data) => {
            data.forEach( (item: any) => {
                // some other code..                
            });
        });
    

    然后我在 ngOnDestroy() 中取消订阅“subscriptionNotifies” -

    ngOnDestroy() {
        this.subscriptionNotifies.unsubscribe();
    }
    

    因此,每次当我导航到不同的路线或退出时,observable 都会被取消订阅。

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      相关资源
      最近更新 更多