我有一个 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) }}
这是parent.ts代码
ngOnInit(): void {
this.itemlistService._updateItemChanged.subscribe(data => {
this.dossierItems = this.dossierItems.filter(d => d.title !== data);
});
}
和 dossierItemsCountString 函数:
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);
}
});
关于javascript - 使用行为主体跨侧组件通信更新计数项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61292682/