我如何使用打字稿计算购物篮中所有产品的价格,angular
how do I calculate the price of all the products in the basket with typescript , angular
我不明白为什么它不起作用,我是堆栈溢出和打字稿的新手,如果我没有正确提出问题,我深表歉意,谢谢!
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 更适合获取订阅的当前值并获得有关更改的通知)。
如果这些值只在这个组件中需要,你也可以想出没有服务的方案。
我不明白为什么它不起作用,我是堆栈溢出和打字稿的新手,如果我没有正确提出问题,我深表歉意,谢谢!
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 更适合获取订阅的当前值并获得有关更改的通知)。
如果这些值只在这个组件中需要,你也可以想出没有服务的方案。