【问题标题】:Unable to remove items using splice within for loop in Angular无法在 Angular 的 for 循环中使用拼接删除项目
【发布时间】:2018-04-16 14:41:47
【问题描述】:

我正在尝试使用 splice 从现有数组中删除一个项目,但没有按预期工作。我什至尝试使用过滤器而不是拼接,但得到了相同的输出。有人可以看看这里的功能并帮助我找出问题所在。

请尝试在此处添加可用项目 - https://08b11a0437.stackblitz.io/products 然后导航到购物车页面并尝试删除每个项目。项目未按预期删除。

相关代码在 cartservice.ts、cartcomponent.ts(removeProductFromCart()) 和 cartcomponent.html - https://stackblitz.com/edit/08b11a0437?file=app%2Fcart%2Fcart.component.ts

【问题讨论】:

  • 您从CartService.addedProductIdArray 数组中删除了项目,但在模板中使用了与服务数组不同步的products 数组。

标签: arrays angular splice


【解决方案1】:

问题是您正在从 cartService 的数组中删除商品,但对于 UI,您使用的是 products 数组中的值。

快速解决方法是重新加载您的产品数组。只需在ShoppingCartComponentremoveProductFromCart 函数中添加以下代码。在函数末尾添加。

this._cartService.getAddedProducts().subscribe((data: IProduct[]) => {
  this.products = data.map(item => item[0]);      
});   

除此之外还有一个问题。您正在使用*ngIf="removeItemId !== product.id" 隐藏ShoppingCartComponent html 中的项目。假设您的购物车中有三个产品(id 为 1,2 和 3),当第一个产品被删除时,removeItemId 将有 1 个,因此第一个产品将被隐藏。但是当用户删除第二个产品时,removeItemId 将被设置为 2,现在产品一将可见。

【讨论】:

  • @Anand Murali 有什么办法可以修改现有数组而不是重新加载数组。我相信这会导致性能问题,因为我不得不重新发送 http 请求,如果有大量产品,这将是一个问题
  • 是的。您已经在 CartService 本身中创建了 products 数组。并将项目删除/添加到此产品数组。要在 html 中绑定到这个数组,只需直接循环 cartService.products 即可。
  • 知道了,谢谢
猜你喜欢
  • 2013-04-19
  • 2011-01-04
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
相关资源
最近更新 更多