Reputation: 775
I am doing shopping cart application, when user deselect item from checklist i need to minus from total amount and i am using Behavioral Subject to update total Amount every time user add or remove via shared service. After minus from total amount, again i am updating Subject value accordingly. But here i am getting error stack exceed.
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);
}
here onItemDeSelect() function executes every time on deselect item then update total amount in shared service. i don't know where i am doing mistake.
Upvotes: 0
Views: 47
Reputation: 3192
Maximum call stack exceeded error will come mostly when the function undergoes infinite recursion. Isn't this obvious in the codee that you have subscribed to something that updates the value again. In your code you are doing
this.shared.updatedAmount(this.totalAmount);
which will update the value and fires an even with the behavior subject
updateAmountValue: BehaviorSubject<number> = new BehaviorSubject(0);
And you have subscribed to this subject which will again update the value and so on which results in a infinite recursive state.
Possible Solution
You can get the value of the subject directly instead of subscribing to it.
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);
}
});
}
This will not result in any recursive condition. Hope this helps.
Upvotes: 0