【发布时间】:2019-04-15 17:22:46
【问题描述】:
我目前正在为 Web 应用程序开发一个简单的聊天(如 Facebook)。 我使用 Angular 6 作为框架,使用 Firebase 作为我的数据库。
当用户点击某个对话时,我会使用 .on("child_added, //function here) 检索以前的消息,然后将结果推送到将使用 *ngFor 循环显示的数组中。
我遇到的奇怪问题是消息有时会正确显示,有时根本不显示。发生这种情况时,只要我单击任意位置,*ngFor 就会再次被调用,一切看起来都很好。
使用console.logs我发现数据每次都被正确推送到数组中,但是由于某种原因,ngFor(与ngAfterViewChecked相同)有时会更新,有时只会返回一个空数组.
我的 .ts 文件(相关部分):
ngAfterViewChecked() {
/*
when everything works, this will be called everytime something changes
(even after the array gets populated)
when the issue comes up, this will be called as usual but it won't be called after the array gets populated,
thus returning an empty array the last time it was called
*/
console.log(this.msgService.messageList)
}
//this will be called everytime a user clicks on a conversation on the left sidebar
getSpecConversation(conversation) {
//emptying the array
this.msgService.messageList = [];
//calling the .off using previous conversation key
this.msgService.getConversation(this.msgService.selectedConversation.$key)
.off('child_added');
//getting messages of currently selected conversation
this.msgService.getConversation(conversation.$key)
.on('child_added', (data => {
//push the data into array
this.msgService.messageList.push(data.val());
})
);
//storing currently selected conversation
this.msgService.selectedConversation = conversation;
}
模板(相关部分):
<ul class="conversation-list">
<li *ngFor="let message of msgService.messageList" class="conversation-item" [class.sender]="message.byUid == userInfoService.userUid">
<p class="message">{{message.msg}}</p>
<p class="msg-time">
<span>{{message.time | date: 'shortTime'}}</span></p>
</li>
</ul>
服务:
getConversation(sid: string) {
return this.database.ref('/messages')
}
感谢您的帮助
更新
如果有帮助,如果我删除 .off('child_added') 方法,问题将不再出现,但是,当我发送新消息时,我会在视图中多次调用新消息(而不是在数据库中)。
【问题讨论】: