如何用typescript计算篮子中所有产品的价格?



我不知道为什么它不起作用,我是堆栈溢出和打字脚本的新手,如果我没有正确地问问题,我道歉,谢谢!

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>

subTotal是从模板调用的函数。card.component.ts中的subTotal函数再次调用cartService.ts中的subTotalPriceMyCart。但是根据你的代码,什么也没有返回。

整个逻辑可以得到改进。您可能希望绑定到实际值,而不是绑定到模板中的函数。为此,您需要在card.component.ts中使用一些变量来存储该值。您可以订阅服务中的主题以获得更改通知并相应地更新存储的值,或者实现一些getter函数来初始检索值(也许一个BehaviorSubject更适合在订阅时获取当前值并在更改时获得通知)。

如果这些值只在这个组件中需要,你也可以考虑一个不需要服务的解决方案。

最新更新