【问题标题】:Can I end a firebase callback in the callback itself?我可以在回调本身中结束 firebase 回调吗?
【发布时间】:2019-10-01 15:40:42
【问题描述】:

我想知道是否有任何方法可以在回调本身内停止回调。我尝试使用 ref.off() 方法来停止它,如下所示,但它仍会继续运行。有什么建议吗?

ref.orderByChild('t').startAt(time.getTime()).on('child_added', function (snapshot) {
  const d = snapshot.val();
  const x = Math.round(d.x * 100).toString();
  const y = Math.round(d.y * 100).toString();
  if (that.selectedEnd && d.t > that.selectedEnd.getTime()) {
    snapshot.ref.off('child_added');
    console.log('STOP');
  } else {
    ....
  }
});

【问题讨论】:

    标签: typescript firebase firebase-realtime-database


    【解决方案1】:

    根据on() 的 API 文档:

    返回函数

    提供的回调函数未经修改返回。这只是 为方便起见,如果您想将内联函数传递给 on() 但是 存储回调函数,以便稍后传递给 off()。

    因此,您可以将其返回值传递给off(),在您调用on() 的同一查询对象上调用:

    const query = ref.orderByChild('t').startAt(time.getTime());
    const listener = query.on('child_added', function (snapshot) {
        ...
        query.off('child_added', listener);
    });
    

    【讨论】:

    • 感谢您的快速响应。但是它在侦听器上给出了一个错误:'(a:DataSnapshot,b?:字符串)=> any'类型的参数不可分配给'EventType'类型的参数。类型 '(a: DataSnapshot, b?: string) => any' 不可分配给类型 '"child_removed"'。像这样尝试过:query.off('child_added', listener) 但它也不起作用。
    • 可能是 TypeScript 绑定有问题。但根据 API 文档,这是你应该这样做的方式。
    猜你喜欢
    • 2013-03-19
    • 2019-12-02
    • 1970-01-01
    • 2017-07-18
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2011-05-20
    相关资源
    最近更新 更多