从Firebase API获取:
Child Added: 此事件将为此位置的每个初始子级触发一次,并且每次添加新子级时都会再次触发。
一些代码:
listRef.on('child_added', function(childSnapshot, prevChildName) {
// do something with the child
});
但由于该函数为此位置的每个子节点调用一次,是否有办法只获取实际添加的子节点?
从Firebase API获取:
Child Added: 此事件将为此位置的每个初始子级触发一次,并且每次添加新子级时都会再次触发。
一些代码:
listRef.on('child_added', function(childSnapshot, prevChildName) {
// do something with the child
});
但由于该函数为此位置的每个子节点调用一次,是否有办法只获取实际添加的子节点?
如果要跟踪自某个检查点以来添加的内容而不获取以前的记录,可以使用endAt()
和limit()
来抓取最后一条记录:
// 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());
});
ref.endAt().limit(1)
返回的记录触发一次。它不会对添加到该记录之后的其他新记录触发。我正在使用 Angularfire 0.8.0 进行测试。 - Waseemlimit()
方法已被弃用。 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());
});
child_added
函数接受两个参数 snapshot
和 prevChildKey
,使用该方法时 prevChildKey
始终为 null。我使用 ref.endAt().on('child_added', function(snapshot, prev) {});
。 - av4625由于调用 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
})
Eg:
last sorted key at time of binding: "b"
insert at "a" -> no trigger (comes before "b")
insert at "bbb" -> triggered
insert at "bb" -> no trigger (comes before "bbb")
insert at "bbbb" -> triggered