首页 > 解决方案 > Angular - 对象参数的更改检测不起作用

问题描述

我有以下组件代码。在我的component.ts我定义了以下内容:

  tickets: Ticket[] = []
  uploadCounts: {[key: string]: number} = {}
  
  ngOnInit() { /* Code to grab Tickets from API, init uploadCounts to 0 for each ticket id */ }

  incrementUploadCount(id: string, increment: number) {
    const counts = { ...this.uploadCounts };  // Copy upload counts
    counts[id]+=increment
    this.uploadCounts = { ...counts };  // Clone counts --> new uploadCounts
    console.log(this.uploadCounts);     // This properly logs the uploadCounts changes, in realtime, but
                                        // results are still not updated in the template.
    this.cdr.detectChanges();           // Manually detect changes
  }

  addFile(ticket: Ticket, file) {
    this.incrementUploadCount(ticket.id, 1);  // Increment the upload count by 1 for this ticket.
    this.ticketSvc.uploadFile(ticket, file).then(res => {
        this.incrementUploadCount(ticket.id, -1);  // Decrease the upload count by 1 for this ticket.
    });
  }

在我的component.html我有:

<ng-container *ngFor="ticket of tickets">
  <h2>{{ ticket.name }}</h2>
  <div *ngIf="uploadCounts[ticket.id] > 0">Uploading {{ uploadCounts[ticket.id] }} files...</div>
</ng-container>

触发时addFile,将添加文件,但是该票证的上传计数 div 不会显示,也不会更新,直到一切都完成后(当它闪烁几毫秒并消失时)。我一直小心地确保uploadCounts每次上传状态的变化都会覆盖整个对象,以便检测到变化(参见incrementUploadCount方法)。我在 SO 上发现的所有其他问题都表明这是问题所在,但在这里似乎没有任何影响。关于为什么会发生这种情况或解决此问题的更好方法的任何想法?

注意:页面上显示了多张工单,每张工单可能有多个上传,因此需要对哪些工单正在上传进行某种索引)。

标签: angularangular-changedetection

解决方案


推荐阅读