You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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); 
}

代码修正说明及优化

核心过滤逻辑是正确的,但存在冗余调用和可优化点:

  1. callFun中重复调用modifyDeleteItem无必要,若无需临时传递删除项名称,可简化调用逻辑
  2. 使用严格不等运算符!==替代!=,避免隐式类型转换导致的判断错误

修正后的代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:02:00