60

从 Firebase API:

已添加子节点:该位置的每个初始子节点都会触发一次此事件,每次添加新子节点时都会再次触发该事件。

一些代码:

listRef.on('child_added', function(childSnapshot, prevChildName) {
    // do something with the child
});

但是由于这个位置的每个孩子都调用了一次函数,有没有办法只获取实际添加的孩子?

4

5 回答 5

44

要跟踪自某个检查点以来添加的内容而不获取以前的记录,您可以使用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());

});
于 2012-08-03T07:28:12.113 回答
38

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());

});
于 2014-12-23T13:24:37.870 回答
7

由于在没有数据的情况下调用该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(),因此无需捕获空数据。

于 2018-01-08T21:59:53.407 回答
4

我尝试了其他答案方式,但至少为最后一个孩子调用了一次。如果您的数据中有时间键,则可以这样做。

ref.orderByChild('createdAt').startAt(Date.now()).on('child_added', ...
于 2017-09-12T10:40:12.507 回答
1

Swift3 解决方案:

您可以通过以下代码检索您之前的数据:

queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in
    //Your code
})

然后通过以下代码观察新数据。

queryRef?.queryLimited(toLast: 1).observe(.childAdded, with: { (snapshot) in
    //Your Code
})
于 2017-07-19T09:49:01.647 回答