【问题标题】:Messaging component is super slow消息组件超级慢
【发布时间】:2019-12-06 11:41:58
【问题描述】:

我有一个消息传递组件,可以在我的系统中与另一个用户编写消息。问题是当我打开组件时,网站变得超级慢,并且在加载消息之前最多需要 15 秒。我可以在代码中做些什么不同的事情以使其正常工作?

allMessages() {
    return this.messages.concat(this.uploadingMessages);
}
<ng-container #messageList *ngFor="let m of allMessages(); let i = index; trackBy: trackByMessageId">
    <div *ngIf="case !== null" [class.unread]="case.hasReadUntilTimestamp < m.timestamp && !m.sender.isMe && !m.setRead">


    <div class="newMessage">
        <div class="newMessage__line"></div>
        <div class="newMessage__line"></div>
    </div>

    <div class="row messageAndHeader line" *ngIf="allMessages()[i - 1]?.sender.id !== m.sender.id; else elseBlock">
    <div class="row messageInfo">
        <div class="profileImg">
            <img *ngIf="m.sender.profileImageUrl !== null" [src]="m.sender.profileImageUrl" />
 *ngIf="m.sender.profileImageUrl === null">
        </div>

【问题讨论】:

  • 请使用正确的标记更新您的问题。标记似乎有一些问题。此外,如果可能,请分享一些示例数据以供使用。
  • 我清楚地看到的原因之一是您在*ngIf 中调用allMessages(),它将在每个更改检测周期调用该函数。
  • 是的,不要在你的角度模板中调用这样的方法。获取组件中的数据,将其存储在变量中,然后在模板中使用该变量。

标签: javascript html arrays angular typescript


【解决方案1】:

在 Angular DOM 中,所有事件都会刷新,所以这里 allMessages() 会被重复调用,所以在 NgOnInit() 中执行此操作,如下所示分配给一个变量

ngOnInit(){
 this.allMesage = this.messages.concat(this.uploadingMessages);
}

并在 compoent.html 中修改代码如下

<ng-container #messageList *ngFor="let m of allMessage; let i = index; trackBy: trackByMessageId">

如果在进行 API 调用后消息被填充,则添加如下所示的异步管道

<ng-container #messageList *ngFor="let m of allMessage | async; let i = index; trackBy: trackByMessageId">

并删除ngif中的调用方法

<div class="row messageAndHeader line" *ngIf="allMessage[i - 1]?.sender.id !== m.sender.id; else elseBlock">

如果是 api 调用,修改 ngOnInit() 中的代码,如下所示

ngOnInit(){
apiCall.subscribe(data=>{
 this.allMesage = data.messages.concat(data.uploadingMessages);
},
error=>{
console.log(error)
})

【讨论】:

  • 我建议还提到*ngIf
  • 添加 ngif 取决于数据的填充位置?
  • 是的@cerbus 你的权利,应该删除 ngif 中的调用方法也改为使用变量名称
  • 我已经按照您所说的 ajaykumpar mp 更改了代码,但现在我的消息根本没有出现,并且我在控制台中没有收到任何错误。我的代码现在看起来像: this.allMesage = this.messages.concat(this.uploadingMessages); HTML: 然后我将所有函数调用改为“m”。
  • 你是如何获取消息的,这是一个 api 调用吗?
猜你喜欢
  • 1970-01-01
  • 2021-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-13
相关资源
最近更新 更多