javascript - 从数组中删除项目时如何使用behaviorSubject
问题描述
我有 Angular 8 应用程序。
我有两个组成部分,比如孩子 - 父母的关系。因此,我从子项中删除了该项目,但该项目在父项(项目列表)中仍然可见。只有在页面刷新后,该项目才会从列表中消失。
所以我有这个服务:
export class ItemListService {
_updateItemChanged = new Subject<any>();
_removeItemChanged = new BehaviorSubject<any>([]);
constructor() {}
}
这是 item.ts - 孩子:
openRemoveDialog() {
const dialogRef = this.dialog.open(ItemRemoveDialogComponent, {
width: '500px',
height: '500px',
data: {
dossierId: this.dossier.id,
item: this.item,
attachments: this.item.attachments
}
});
this.itemListService._removeItemChanged.next(this.item.title);
dialogRef.afterClosed().subscribe(result => {
if (result === true) {
this.router.navigate(['/dossier', this.dossier.id]);
}
});
}
这是 view.ts(item list) - parent:所以在这个组件中必须进行刷新
ngOnInit(): void {
this.show = !this.router.url.includes('/item/');
this.itemlistService._updateItemChanged.subscribe(data => {
const index = this.dossierItems.findIndex(a => a.id === data.id);
this.dossierItems[index] = data;
});
this.itemlistService._removeItemChanged.subscribe(data => {
// this.dossierItems.pop(); What I have to fill in here?
});
那么我必须改变什么?
谢谢
这是删除功能:
remove() {
this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
.subscribe(() => {
this.dialogRef.close(true);
}, (error) => {
const processedErrors = this.errorProcessor.process(error);
this.globalErrors = processedErrors.getGlobalValidationErrors();
});
}
我现在有这样的:
remove() {
this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
.subscribe(() => {
this.dialogRef.close(true);
this.itemListService._removeItemChanged.next(true);
}, (error) => {
const processedErrors = this.errorProcessor.process(error);
this.globalErrors = processedErrors.getGlobalValidationErrors();
});
}
在 view.ts 中,像这样:
ngOnInit(): void {
this.itemlistService._removeItemChanged.subscribe(update => update === true ? this.dossierItems : '');
}
但仍然不会刷新列表
解决方案
您需要为您的数组创建一个新引用,以便 Angular 像这样更新屏幕
this.itemlistService._removeItemChanged.subscribe(data => {
// this.dossierItems.pop(); What I have to fill in here?
this.dossierItems = this.dossierItems.filter(e => e.title !== data);
});
推荐阅读
- twilio - Twilio 错误 11200 - HTTP 检索失败:尝试检索媒体失败,同时尝试通过 Rest API 触发 Twilio Studio 流执行
- r - 合并数据框,保留数据集 A 中的所有行
- google-colaboratory - 在 Colab 中如何与 Google Drive 同步?
- javascript - Mongoose findOneAndUpdate() 最新索引
- ios - 如果 #available(iOS 14.0, *) { }
- c# - 请求在 IIS 上停留在 BeginRequest 状态
- java - Grizzly 2.4 Embedded Https Server 在 NEED_WRAP 上无限循环
- javascript - 如何在 GEE 中使用 shapefile 资产作为 AOI?
- c# - 无法修复 SonarCloud 上的 SQL 注入
- reactjs - 删除行时更新单元格背景颜色。(反应表)