如何在Angular服务中订阅变量值的更改?
我已经做了很多搜索,但是找不到解决方案(即使有可能!)。
我有一个component
,这是我的布局(标题)的一部分,其中显示了购物车中的物品数量。该值绑定到变量simsInCartLength
然后我有一个service
来处理购物车中物品的添加和删除。在service
中,我有一个名为noSims
的变量,用于存储购物车中商品数组的长度。
我如何订阅对服务变量noSims的更改?
组件中的代码
simsInCartLength = this.cartService.noSims;
我的服务中的代码(在购物车中添加或删除商品时,变量会更新:
this.noSims = this.simsInCart.length;
提前谢谢!
答案 0 :(得分:4)
尝试如下在服务中使用BehaviorSubject
:
private cartItemCount = new BehaviorSubject<number>(0);
cartItem = [];
getCartItemCount(){
return this.cartItemCount.asObservable();
}
addToCart(obj: any){
this.cartItem.push(obj);
// some operation to add item in cart and then call next() of observable to emit the new value event
this.cartItemCount.next(this.cartItem.length)
}
// similar code for removeFromCart()
和您组件中的订阅该事件的方式为:
ngOnInit(){
this.cartService.getCartItemCount().subscribe(len => {
console.log(len) // your new cart length here
this.simsInCartLength = len;
})
}