sourcecode

Firebase child_added only get child added

codebag 2023. 7. 12. 23:45
반응형

Firebase child_added only get child added

Firebase API에서:

추가된 자식:이 이벤트는 이 위치의 각 초기 자식에 대해 한 번씩 트리거되며, 새 자식이 추가될 때마다 다시 트리거됩니다.

일부 코드:

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

});

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
})

언급URL : https://stackoverflow.com/questions/11788902/firebase-child-added-only-get-child-added

반응형