取消订阅Firebase实时数据库 [英] Unsubscribing from Firebase Realtime Database

查看:48
本文介绍了取消订阅Firebase实时数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Ionic应用程序中有一个聊天系统,该系统显示在模式窗口中.在模态窗口中,我有下面的代码.似乎在使用该应用程序一段时间后,它变得有点迟钝.

我怀疑这是因为当我关闭模式窗口时,我应该取消订阅Firebase.换句话说,每次单击按钮以打开模态时,似乎正在进行新的订阅.是这样吗如果是这样,我该怎么办?我在文档中没有看到退订选项?

  ionViewDidLoad(){firebase.database().ref('chatrooms/'+ this.roomkey +'/chats').limitToLast(30).on('value',resp => {this.chats = [];this.chats = snapshotToArray(resp);this.content.scrollTo(0,999999,200);});} 

我已经尝试了以下方法来调用 off ,但是不确定这是否是正确的方法?我把它放在 ionViewDidLeave()

  firebase.database().ref('chatrooms/'+ this.roomkey +'/chats').limitToLast(30).off('value'); 

解决方案

当不再需要该数据库侦听器时,应始终删除该数据库侦听器上的所有侦听器.否则,当数据更改时,该侦听器将继续接收快照.

要删除侦听器,请使用 off()与您用来调用 on()的引用相同的方法.向其传递您在on()上传递的回调函数.另请阅读分配侦听器的文档.>

I have a chat system within my Ionic app that is displayed within a modal window. Within the modal window I have the code below. It seems that after using the app for a while it becomes a bit sluggish.

I suspect that it's because I should be unsubscribing from Firebase when I close the modal window. In other words, it seems like a new subscription is being made each time I click the button to open the modal. Is this the case? If so, what should I do? I don't see an unsubscribe option in the docs?

ionViewDidLoad() {
    firebase.database().ref('chatrooms/'+this.roomkey+'/chats').limitToLast(30).on('value', resp => {

        this.chats = [];
        this.chats = snapshotToArray(resp);
        this.content.scrollTo(0, 999999, 200);

    });
}

I have tried the following to call off but unsure if it is the correct approach? I have put this within ionViewDidLeave()

firebase.database().ref('chatrooms/'+this.roomkey+'/chats').limitToLast(30).off('value');

解决方案

You should always remove any listeners on a database reference when that listener is no longer needed. Otherwise, that listener will continue to receive snapshots when data changes.

To remove a listener, use the off() method on the same reference that you used to call on(). Pass it the callback function that you passed on on(). Please also read the documentation for detatching listeners.

这篇关于取消订阅Firebase实时数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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