i have a total price in BehavoiurSubject
export class ShoppingCartService {`
public totalPriceSubject = new BehaviorSubject<number> (this.getTotalPrice(this.loadOrderedProducts()));
getTotalPrice(selectedProducts: SelectedProductOrderModel[]): number {
let totalPrice = 0;
for (const orderedProduct of selectedProducts) {
totalPrice = orderedProduct.quantity * orderedProduct.product!.price;
}
return totalPrice;
}
}
i display it in shopping cart component.ts
export class ShoppingCartComponent implements OnInit {
totalPrice: number;
private totalPriceSub: Subscription;
ngOnInit(): void {
this.usersSelectedProducts = JSON.parse(<string>localStorage.getItem('selectedProductOrders'));
this.totalPriceSub = this.cartService.totalPriceSubject
.subscribe(totalPrice => {
this.totalPrice = totalPrice;
});
}
.html
<td>${{totalPrice}}</td>
but when i m adding one more product in shopping cart component, totalPrice doesnt update, i need to refresh page and then i get new number. Can anyone please advise me how to solve it, i want it after i add one more product it will update totalPrice. thx
CodePudding user response:
Try to do following changes in your service files
export class ShoppingCartService {
calTotalPrice = (selectedProducts: SelectedProductOrderModel[]) : number => {
let totalPrice = 0;
for (const orderedProduct of selectedProducts) {
totalPrice = orderedProduct.quantity * orderedProduct.product!.price;
}
return totalPrice;
}
public totalPriceSubject = new BehaviorSubject<number>(this.calTotalPrice(cartItemList))
totalPrice = this.totalPriceSubject.asObservable();
constructor() { }
setTotalPrice(price: number) {
this.totalPriceSubject.next(price);
}
}
In your component, you can subscribe and receive the values.
this.totalPriceSub = this.cartService.totalPrice
.subscribe(totalPrice => {
this.totalPrice = totalPrice;
});