从 Firebase API:
已添加子节点:该位置的每个初始子节点都会触发一次此事件,每次添加新子节点时都会再次触发该事件。
一些代码:
listRef.on('child_added', function(childSnapshot, prevChildName) {
// do something with the child
});
但是由于这个位置的每个孩子都调用了一次函数,有没有办法只获取实际添加的孩子?
从 Firebase API:
已添加子节点:该位置的每个初始子节点都会触发一次此事件,每次添加新子节点时都会再次触发该事件。
一些代码:
listRef.on('child_added', function(childSnapshot, prevChildName) {
// do something with the child
});
但是由于这个位置的每个孩子都调用了一次函数,有没有办法只获取实际添加的孩子?
要跟踪自某个检查点以来添加的内容而不获取以前的记录,您可以使用endAt()
andlimit()
获取最后一条记录:
// retrieve the last record from `ref`
ref.endAt().limitToLast(1).on('child_added', function(snapshot) {
// all records after the last continue to invoke this function
console.log(snapshot.name(), snapshot.val());
});
limit()
方法已弃用。limitToLast()
和limitToFirst()
方法替换它。
// retrieve the last record from `ref`
ref.limitToLast(1).on('child_added', function(snapshot) {
// all records after the last continue to invoke this function
console.log(snapshot.name(), snapshot.val());
// get the last inserted key
console.log(snapshot.key());
});
由于在没有数据的情况下调用该ref.push()
方法会根据时间生成路径键,这就是我所做的:
// Get your base reference
const messagesRef = firebase.database().ref().child("messages");
// Get a firebase generated key, based on current time
const startKey = messagesRef.push().key;
// 'startAt' this key, equivalent to 'start from the present second'
messagesRef.orderByKey().startAt(startKey)
.on("child_added",
(snapshot)=>{ /*Do something with future children*/}
);
请注意,实际上没有将任何内容写入返回的引用(或“键”)ref.push()
,因此无需捕获空数据。
我尝试了其他答案方式,但至少为最后一个孩子调用了一次。如果您的数据中有时间键,则可以这样做。
ref.orderByChild('createdAt').startAt(Date.now()).on('child_added', ...
Swift3 解决方案:
您可以通过以下代码检索您之前的数据:
queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in
//Your code
})
然后通过以下代码观察新数据。
queryRef?.queryLimited(toLast: 1).observe(.childAdded, with: { (snapshot) in
//Your Code
})