我試圖在使用Firebase作爲其數據集的Angular 4聊天應用程序中「延遲加載」消息。附加FirebaseListObservable並使用endAt
這裏的想法是在第一次加載應用程序時檢索x數量的消息(現在數量爲3以便於調試),並在用戶滾動到頂部或按下'更多'按鈕時加載更多消息。 我寫了一個函數加載消息:
public retrieveMessages(conversationId, end?) {
const LIMIT_TO_LAST = 3;
if (this.firebaseUserIsAuthenticated()) {
if (end != null) {
console.log('retrieving next 10');
this.messages.subscribe(messages => {
const topMessage = messages[0].$key;
console.log('Top message: ' + topMessage);
const ref = this.firebaseApp.database().ref('messages/' + conversationId);
ref.orderByChild('id').endAt(topMessage).limitToLast(LIMIT_TO_LAST).on('child_added', function (snapshot) { // This gives us the top message + 'LIMIT_TO_LAST'-1 before it
console.log(snapshot.val());
messages.unshift(snapshot.val());
});
console.log(messages);
});
} else {
console.log('retrieving first 10');
this.messages = this.db.list('messages/' + conversationId, { query: { limitToLast: LIMIT_TO_LAST } });
}
this.messages.subscribe(messages => {
console.log('Retrieved messages for conversation with id ' + conversationId + '.');
});
}
}
問題1:我需要一個 'endBefore' 而不是 'ENDAT'
這裏的第一個問題是, 'ENDAT' 給出我記錄包括與 'ENDAT' 值。:
初始消息數組= [消息13] [消息14] [消息15]
新記錄消息陣列= [消息11] [消息12] [消息13] [消息13] [消息14] [消息15]
我可以limitToLast(LIMIT_TO_LAST + 1)並刪除最後一個對象,但那很醜。這樣做的正確方法是什麼? 我想爲每條消息添加一個timestamp鍵(有一個毫秒值),按這個時間戳鍵排序,然後說我們需要所有的消息「topMessage.timestamp - 1」。我還沒有測試過這是否會起作用(我不知道endAt鍵是否存在),但是當有兩條消息具有完全相同的時間戳時,這會產生問題,儘管這種情況不太可能發生。
僅限使用limitToLast在這裏不是一個選項(第一次調用:limitToLast(3),第二次調用:limitToLast(6)等等),因爲這並不意味着我們只在檢索到3個時才顯示3條消息假設我們檢索了3條消息,但有人寫了一條新消息,它也會被顯示(所以現在我們有4條消息)。如果用戶按下'loadMore',則只會加載2條新消息,而不是3條。 當我們加載3條消息,發送4條消息,然後檢索'3條以上消息'時,這個問題會更加嚴重。然後,它會直接刪除第一個...
問題2:追加郵件列表:
this.messages是FirebaseListObservable <>在這一刻。 據我所知,這是不可能追加此列表與新檢索的消息。 我想創建一個this.messageObjects(或東西)與持有一個消息對象數組。每次我檢索更多消息時,我都可以追加該數組。 這是個好主意嗎?或者,還有更好的方法?
其他信息
我使用火力的ID(-K3d - f3e2 ...),所以我不能簡單地說 'ENDAT - 1' 或什麼的。