角度-对对象参数的更改检测不起作用

问题描述

我有以下组件代码。在我的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上发现的所有其他问题都表明这是问题所在,但在这里似乎没有任何作用。有什么想法可能会发生这种情况,或者有更好的解决方案?

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)