angular - 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 上发现的所有其他问题都表明这是问题所在,但在这里似乎没有任何影响。关于为什么会发生这种情况或解决此问题的更好方法的任何想法?
注意:页面上显示了多张工单,每张工单可能有多个上传,因此需要对哪些工单正在上传进行某种索引)。
解决方案
推荐阅读
- python - 读入一个 10 个字符的字符串并在新行上打印出每个字符
- python - Ansible 库存脚本需要 requests 模块,我如何将包安装到 Ansible 本身?
- python - 如何在显示数据的每一行中添加输入?
- firebase - Firebase Cloud Functions shell:添加身份验证令牌以调用可调用对象
- oracle - 为飞行路线的基线创建 DDL
- java - 为什么我的线性分类器(感知器)能够对非线性可分数据进行分类?
- excel - Excel中多列文本的总和
- node.js - 如何一次删除超过 100 条消息?
- list - 在 sharepoint 中添加子类别
- elasticsearch - Elasticsearch 使用通配符模式更改多个别名