问题描述
我有一个Firebase中的节点不断更新来自日志文件的信息。节点是 lines /
, lines /
的每个子节点都来自 post() / code>所以它有一个唯一的ID。
当客户端第一次加载时,我希望能够抓住最后一个 X
条目数量。我希望我会用 once()
来做到这一点。从那时起,我想用 on()
和 child_added
来获取所有新数据。但是, child_added
会获取存储在Firebase中的所有数据,并且在初始设置之后,只需要新的东西。
我看到我可以在 on()
上添加 limitToLast()
但是,如果我说 limitToLast(1)
和大量的条目进来,我的应用程序仍然会得到所有新的条目?有没有其他的方法来做到这一点?
解决方案 您需要包含 timestamp
属性并运行查询。
//获取当前时间戳
var now = new Date()。getTime();
//创建一个按时间戳命令的查询
var query = ref.orderByChild('timestamp')。startAt(now);
//监听从这个时间点添加的新孩子
query.on('child_added',function(snap){
console.log(snap.val()
});
//当你添加这个新的项目时,它会触发
上面的查询ref.push({
title:hello,
时间戳:Firebase.ServerValue.TIMESTAMP
});
, orderByChild()
和用于创建范围 startAt()
的方法。从Firebase返回。
I have a node in Firebase getting continually updated with information from a logfile. The node is lines/
and each child of lines/
is from a post()
so it has a unique ID.
When a client first loads, I want to be able to grab the last X
number of entries. I expect I'll do this with once()
. From then on, however, I want to use an on()
with child_added
so that I get all new data. However, child_added
gets all data stored in the Firebase and, after the initial setup, only want the new stuff.
I see that I can add a limitToLast()
on the on()
, but, if I say limitToLast(1)
and a flood of entries come in, will my app still get all the new entries? Is there some other way to do this?
解决方案 You need to include a timestamp
property and run a query.
// Get the current timestamp
var now = new Date().getTime();
// Create a query that orders by the timestamp
var query = ref.orderByChild('timestamp').startAt(now);
// Listen for the new children added from that point in time
query.on('child_added', function (snap) {
console.log(snap.val()
});
// When you add this new item it will fire off the query above
ref.push({
title: "hello",
timestamp: Firebase.ServerValue.TIMESTAMP
});
The Firebase SDK has methods for ordering, orderByChild()
and methods for creating a range startAt()
. When you combine the two you can limit what comes back from Firebase.
这篇关于如何在没有Firebase现有数据的情况下获取新数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!