首页 > 解决方案 > 范围误差最大调用堆栈超出角度 6

问题描述

我正在做购物车应用程序,当用户从清单中取消选择项目时,我需要从总金额中减去,并且每次用户通过共享服务添加或删除时,我都使用行为主题来更新总金额。在从总量中减去之后,我再次相应地更新主题值。但在这里我得到错误堆栈超出。

onItemDeSelect(uncheckedItem) {
    this.eachItem.itemExtraOptionPrice.prices.forEach(item => {
      this.shared.updateAmountValue.subscribe(value => {
        if (item.id === uncheckedItem.id) {
          this.totalAmount = value - item.amount;
          this.shared.updatedAmount(this.totalAmount);
        }
      });
    });
}

updateAmountValue: BehaviorSubject<number> = new BehaviorSubject(0);

  updatedAmount(value) {
    this.updateAmountValue.next(value);
  }

这里 onItemDeSelect() 函数每次在取消选择项目时执行,然后更新共享服务中的总量。我不知道我在哪里做错了。

标签: javascriptangular

解决方案


最大调用堆栈超出错误主要发生在函数进行无限递归时。在您订阅了再次更新值的代码的代码中,这不是很明显吗?在你的代码中你正在做

this.shared.updatedAmount(this.totalAmount);

这将更新值并触发与行为主题的偶数

updateAmountValue: BehaviorSubject<number> = new BehaviorSubject(0);

而且您已经订阅了这个主题,它将再次更新值等等,这会导致无限递归状态。

可能的解决方案

您可以直接获取主题的值,而不是订阅它。

onItemDeSelect(uncheckedItem) {
    this.eachItem.itemExtraOptionPrice.prices.forEach(item => {
      let value = this.updateAmountValue.getValue();
        if (item.id === uncheckedItem.id) {
          this.totalAmount = value - item.amount;
          this.shared.updatedAmount(this.totalAmount);
        }
    });
}

这不会导致任何递归条件。希望这可以帮助。


推荐阅读