【发布时间】:2019-06-28 20:05:58
【问题描述】:
我订阅获取用户聊天,然后对于每个聊天,我订阅另外两个 observables。
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>
除了聊天最后一条消息不会在前端自动更新之外,这是可行的,我理解为什么这不起作用,我将观察者推入一个数组,该数组失去了监听更改的功能,但我不能不知道如何在不从两个不同的订阅者推送对象的情况下收听更改并正确显示它们。我基本上每次都要重新加载聊天列表才能看到变化。
最好用图片来说明:
我向 Holly 发送了另一条消息,最后一条消息现在应该是“B”
但是如果不刷新页面,最后一条消息不会更新,它不会监听更改,因为我正在将 observable 推送到数组中
1:1 聊天的 Firebase 实时数据库结构
【问题讨论】:
标签: javascript firebase firebase-realtime-database observable angularfire