我正在尝试使用orderBy方法和limit(1)从集合中获取最后一个文档,一切正常,并且可以按预期工作,但是问题是当我从其他地方(例如firebase)向集合中添加新文档时在控制台中打开应用程序中的同一页面时,尽管我指定了limit(1),但我得到了最后两个文档。当我刷新页面时,一切顺利。我该如何解决这个问题?预先感谢。
-这是我的一些代码:
首先使我的聊天顺序降序,然后从chatUsers集合中获取朋友的详细信息,最后获取最后一个消息文档。
chat-provider.ts
getChats() {
return this.afs.collection(`chatUsers/${this.userId}/chats` , ref => ref.orderBy('updatedAt' , 'desc')).valueChanges()
}
getlastMessage(friendId : string) {
return this.afs.collection(`chatUsers/${this.userId}/chats/${friendId}/messages` , ref => ref.limit(1).orderBy('createdAt' , 'desc')).valueChanges();
}
auth-provider.ts
getUser(userId) : Observable<ChatUser> {
return this.afs.doc<ChatUser>(`chatUsers/${userId}`).valueChanges();
}
page.ts
ionViewWillEnter(){
// get chats
this.chatService.getChats()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((friends : Friend[]) => {
let chats = [];
friends.forEach(friend =>{
//get friend Dtails
this.chatService.authService.getUser(friend.friendId)
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(friendDetails => {
//get last message
this.chatService.getlastMessage(friendDetails.uid)
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((lastMessage : any) => {
let Chat : ChatMsg = {
friend : friendDetails,
lastMsg : lastMessage
}
chats.push(Chat);
})
})
})
this.zone.run(() => {
this.chats = chats;
})
});
}