Home > Enterprise >  how do I calculate the price of all the products in the basket with typescript , angular
how do I calculate the price of all the products in the basket with typescript , angular

Time:05-17

I do not realize why it does not work, I am new to stack overflow and typescript, I apologize if I do not ask the question correctly, thanks !

cartService.ts

cartProducts: Product[] = [];

subTotalPrice : Subject<number> = new Subject<number>();
totalQuantityy :Subject<number> = new Subject<number>();

subTotalPriceMyCart(){

let subTotalPriceValue :number = 0;
let totalQuantityValue :number = 0;

for(let currentCartItem of this.cartProducts){
  subTotalPriceValue  = currentCartItem.quantity * currentCartItem.price;
  totalQuantityValue  = currentCartItem.quantity;
}

this.subTotalPrice.next(subTotalPriceValue);
this.totalQuantityy.next(totalQuantityValue);

}

cart.component.ts

subTotal(){
this.cartService.subTotalPriceMyCart();

}

cart.component.html

<h2>Order Summary</h2><hr>
<h5 >{{subTotal()}}</h5>

CodePudding user response:

subTotal is a function that is called from your template. The subTotal function in card.component.ts again calls subTotalPriceMyCart in cartService.ts. But according to your code nothing is returned.

The whole logic can be improved. Instead of binding to a function in your template, you probably want to bind to the actual value. To do so, you need some variable in your card.component.ts that stores that value. You can subscribe to the subjects in your service to get notified of changes and update the stored value accordingly or implement some getter function to retrieve the value initially (maybe a BehaviorSubject would be a better fit to get the current value on subscription and to get notified on changes).

If those values are only needed in this component, you can also think of a solution without a service.

  • Related