Angular 9中如何通过Service移除数组中的指定对象
问题:点击按钮移除数组中指定name属性的对象(Angular实现)
需要点击“Remove Name”按钮时,从数组中移除name属性为Test1的对象,目前已通过Angular Service尝试更新数组,但不确定实现是否正确,请求修正代码。
现有代码
dashboard.component.html
<button (click)="callFun('Test1')">Remove Name</button> {{ deleteItemName }} <app-optymodel></app-optymodel>
dashboard.component.ts
callFun(name: any) { this.commonService.modifyDeleteItem(name); this.commonService.modifyNameList(name); this.commonService.modifyDeleteItem(''); }
common.service.ts
modifyNameList(name: string) { const nameList = this.nameList.getValue(); const result = nameList.filter((x) => x.name != name); this.nameList.next(result); } modifyDeleteItem(name: string) { this.deletedItem.next(name); }
代码修正说明及优化
核心过滤逻辑是正确的,但存在冗余调用和可优化点:
callFun中重复调用modifyDeleteItem无必要,若无需临时传递删除项名称,可简化调用逻辑- 使用严格不等运算符
!==替代!=,避免隐式类型转换导致的判断错误
修正后的代码
dashboard.component.ts(简化调用)
callFun(name: string) { this.commonService.modifyNameList(name); }
common.service.ts(优化过滤逻辑)
modifyNameList(name: string) { const currentList = this.nameList.getValue(); const updatedList = currentList.filter(item => item.name !== name); this.nameList.next(updatedList); } // 若无需传递删除项名称给其他组件,可根据实际需求保留或移除该方法 modifyDeleteItem(name: string) { this.deletedItem.next(name); }
期望执行结果
点击按钮后,数组将过滤掉name为Test1的对象,输出结果如下:
[ { name: 'Test2', id: '2' }, { name: 'Test3', id: '3' }, { name: 'Test4', id: '4' }, { name: 'Test5', id: '5' }, ];
内容的提问来源于stack exchange,提问作者EMahan K
相关产品推荐
相关产品推荐

