我有一个angular 8应用程序。我有两个组成部分。一个可以编辑项目的组件。还有一个组件,您可以在其中查看所有项目。这些物品分为四类。每个类别都有一个计数器,用于统计每个类别中的项目。如果我加上一个项目,计数器就会增加,所以这是正确的。但是如果我删除了一个项目。计数器不会减少。
所以我有这个服务:
_updateItemChanged = new BehaviorSubject<any>([]);
constructor() {}
}
这就是
可以删除项目子组件的组件:
remove() {
this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
.subscribe(() => {
this.dialogRef.close(true);
this.itemListService._updateItemChanged.next(this.data.item.title);
}, (error) => {
const processedErrors = this.errorProcessor.process(error);
this.globalErrors = processedErrors.getGlobalValidationErrors();
});
}
这是父组件.html:
<span i18n>Action steps</span>{{ dossierItemsCountString(itemTypes.ActionStep) }}
这是父母的代码
ngOnInit(): void {
this.itemlistService._updateItemChanged.subscribe(data => {
this.dossierItems = this.dossierItems.filter(d => d.title !== data);
});
}
和档案项目计数字符串函数:
dossierItemsCountBy(itemType: DossierItemTypeDto) {
return this.typeSearchMatches[itemType.toString()] || { total: 0, matches: 0 };
}
dossierItemsCountString(itemType: DossierItemTypeDto) {
const count = this.dossierItemsCountBy(itemType);
if (this.hasSearchQuery) {
return `(${count.matches}/${count.total})`;
} else {
return `(${count.total})`;
}
}
所以我必须改变的是,如果你删除了一个项目,那么在父组件中,计数器也会减少。
谢谢
经过讨论,我们发现问题出在组件之间的混合指针上,解决这个问题的正确方法是操作原始数组,而不是创建新数组。
解决方案:
this.itemlistService._updateItemRemoved.subscribe(data => {
const index = this.dossierItems.findIndex(a => a.id === data.id);
if (index !== -1) {
this.dossierItems.splice(index, 1);
}
});