我正在开发在前端使用angular的购物车模块。我有两个组成部分。一个是NavBar组件,另一个是ProductCard组件。我想在ProductCard Component中单击添加到购物车按钮时更新NavBar Component中的总量。但是在ProductCard Component上单击添加到购物车时,NavBar Component中的总量未更新。总数量仅在刷新页面时更新。 / p>
我正在使用BehaviourSubject在组件之间进行通信。但没有结果。
shopping-cart.services.ts
@Injectable()
export class ShoppingCartService {
qtyInCarts = new BehaviorSubject(this.countTotalQuantity());
getTotalCartQty = this.qtyInCarts.asObservable();
constructor(private globalService: GlobalService,
private http: HttpClient) {}
setTotalCartQty(qty: number) {
this.qtyInCarts.next(qty);
}
countTotalQuantity() {
const cartId = JSON.parse(localStorage.getItem('cartId'));
let totalQty = 0;
if (cartId) {
this.getCarts()
.subscribe(shopping_cart => {
const carts = shopping_cart['carts'];
for (let i = 0; i < carts.length; i++) {
totalQty += carts[i].qty;
}
this.setTotalCartQty(totalQty);
return totalQty;
});
}
return totalQty;
}
}
bs-navbar.component.ts
export class BsNavbarComponent implements OnInit {
totalQtyInCarts: number;
constructor(private shoppingCartService: ShoppingCartService) {}
ngOnInit() {
this.shoppingCartService.getTotalCartQty
.subscribe((qty) => {
this.totalQtyInCarts = qty;
console.log(this.totalQtyInCarts);
});
}
}
product-card.component.ts
constructor(private cartService: ShoppingCartService) {}
ngOnInit() {
this.cartService.getTotalCartQty
.subscribe((qty) => {
this.totalQtyInCarts = qty;
});
}
addToCart() {
this.cartService.addProductToCart(this.product);
this.totalQtyInCarts += 1;
this.cartService.setTotalCartQty(this.totalQtyInCarts);
console.log(this.totalQtyInCarts);
}
我希望当我单击ProductCardComponent上的添加到购物车按钮时,navBar数量会更新。