我正在创建一个聊天应用程序,当大量消息同时发送时,性能很慢。消息会显示,但UI会在一段时间内变得没有响应。下面是代码的简化版本,我如何解决这个问题?
HTML:
<div class="message-notification" *ngFor="let newMessage of chatMessages"; trackBy: trackByMsgs>
<custom-notification [incomingChat]="newMessage" (dismissedEvent)="onDismiss($event)" (closedEvent)="onNotifcationClose($event)"></custom-notification>
</div>TS:
newChatMessages: any[];
constructor(private chatService: ChatService) {}
ngOnInit() {
this.chatService.chatMsg.subscribe((msg:any) => {
if (msg) {
this.activatePopup(msg);
}
}
activatePopup(message) {
if (message.msgId !== null && message.title !== null) {
this.setTitle(message);
//If popup is already open then do not display a duplicate popup for the same message
let index = this.isPopupOpen(message);
if (index === -1) {
newChatMessages.push(message);
}else {
newChatMessages[index] = message;
}
}
}
trackByMsgs(index:number, msg:any) {
return msg.msgId && msg.title;
}
isPopUpOpen(message){
let index = -1;
if (this.newChatMessages){
index = this.newChatMessages.findIndex(
msg => msg.id === message.id && msg.title === message.title);
}
return index;
}发布于 2021-12-07 23:09:23
在您的情况下,最好是手动控制角度变化检测使用OnPush变化检测策略。您应该小心地使用它,因为当它打开时,只有当onChanges生命周期被触发或者异步管道收到了新的值时,角才会检测到变化。它也适用于所有组件子组件。
然后,您需要通过在组件中注入ChangeDetectorRef来手动检测更改,并在每次要将数据更改应用到您的dom时调用方法detectChanges。
阅读此文章以更好地理解
另一篇有趣的文章,用于改进角应用程序https://medium.com/swlh/angular-performance-optimization-techniques-5b7ca0808f8b的性能。
使用trackBy可以帮助角度记忆ngFor中加载的元素,并且在检测更改时只更新一次更改。但是您的trackByMsgs返回一个布尔值,这不是它应该返回的值。如果调整trackBy以返回唯一的键(如msg.msgId或项的索引),则可能会看到差异。
https://stackoverflow.com/questions/70263695
复制相似问题