我订阅获取用户的聊天记录,然后每个聊天,我订阅其他两种观测。
get_user_chat(chat) {
let user = this.firebase.get_user_by_uid(chat.key).snapshotChanges();
let chatInfo = this.firebase.get_single_chat(chat.payload.val()).snapshotChanges();
return Observable.forkJoin(user.take(1), chatInfo.take(1));
}
getChats() {
//start loading
let loading = this.loadingCtrl.create();
loading.present();
//get chats
this.firebase.get_user_chats().snapshotChanges().takeUntil(this.ngUnsubscribe).subscribe(chats => {
chats.forEach(chat => {
this.get_user_chat(chat).takeUntil(this.ngUnsubscribe).subscribe(userChat => {
this.userChat = userChat;
this.user = this.userChat[0];
this.chat = this.userChat[1];
this.chats.push({
firstName: this.user.payload.val().firstName,
imageUrl: this.user.payload.val().imageUrl,
uid: this.user.key,
chatId: chat.payload.val(),
last_message: this.chat.payload.val().last_message.message,
type: this.chat.payload.val().last_message.type
})
})
})
//dimiss loading
loading.dismiss();
}, err => {
//dimiss loading
loading.dismiss();
})
}
现在的前端,我显示这样的数据:
<ion-content>
<ion-list class="chat-list" *ngIf="(chats)?.length>0">
<a ion-item detail-none *ngFor="let c of chats" (click)="toChat(c.chatId, c.uid)">
<ion-thumbnail item-start>
<img-loader class="img-logo" src={{c.imageUrl}} fallbackUrl="assets/img/placeholder-person.png" useImg></img-loader>
</ion-thumbnail>
<h2>{{c.firstName}}</h2>
<h3 *ngIf="c.type!='img'">{{c.last_message}}</h3>
<img class="img-placeholder" *ngIf="c.type=='img'" src="assets/img/placeholder-image.png">
<!-- <ion-icon item-right name="ios-arrow-forward"></ion-icon> -->
</a>
</ion-list>
<ion-card *ngIf="(chats)?.length==0">
<ion-card-content>
You don't have any chats.
</ion-card-content>
</ion-card>
</ion-content>
这是工作,只是聊天最后的消息不会在前端,我明白这是为什么不工作,我推观察者成失去功能收听改变一个数组,自动更新,但我想不出如何我可以听而不从两个不同的用户推动的对象的变化并正确显示。我基本上每次都看到的变化重新加载聊天列表。
这是更好用图片解释说:
但是,最后的消息不会而无需刷新页面更新,它不听的变化,因为我推可观察到一个数组
1火力地堡实时数据库结构:1个聊天
我强烈建议每个聊天室作为公司的FireStore集合建模。这样一来,如果你有一个聊天室/收集Brendan和霍莉之间的聊天,你只从单个集合阅读,而不是两个。这也使得它更容易保持信息以正确的顺序,因为你可以使用一个单一的查询来获取他们。
对于这样的例子看Best way to manage Chat channels in Firebase。虽然这个问题是关于实时数据库,相同的逻辑可被应用于云公司的FireStore。