我不知道為什么它不起作用,我是堆疊溢位和打字稿的新手,如果我沒有正確提出問題,我深表歉意,謝謝!
購物車服務.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);
}
購物車.component.ts
subTotal(){
this.cartService.subTotalPriceMyCart();
}
購物車.component.html
<h2>Order Summary</h2><hr>
<h5 >{{subTotal()}}</h5>
uj5u.com熱心網友回復:
subTotal是從您的模板呼叫的函式。insubTotal函式card.component.ts再次呼叫subTotalPriceMyCartin 。cartService.ts但是根據您的代碼,沒有回傳任何內容。
整個邏輯可以改進。您可能希望系結到實際值,而不是系結到模板中的函式。為此,您需要一些變數card.component.ts來存盤該值。您可以訂閱服務中的主題以獲得更改通知并相應地更新存盤的值,或者實作一些 getter 函式來最初檢索值(也許 BehaviorSubject 更適合獲取訂閱的當前值并獲得通知關于變化)。
如果這些值只在這個組件中需要,你也可以考慮一個沒有服務的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476043.html
