繁体   English   中英

订阅Angular服务中变量值的更改

[英]Subscribe to the change in the value of a variable in an Angular service

如何在Angular服务中订阅变量值的更改?

我已经做了很多搜索,但是找不到解决方案(即使有可能!)。

我有一个component是布局(标题)的一部分,该组件显示购物车中的项目数。 此值绑定到变量simsInCartLength

然后,我有一个service来处理购物车中物品的添加和删除。 service我有一个名为noSims的变量,用于存储购物车中商品数组的长度。

如何订阅对服务变量noSims所做的更改?

我的组件中的代码:

simsInCartLength = this.cartService.noSims;

我的服务中的代码(在购物车中添加或删除商品时,变量会更新:

this.noSims = this.simsInCart.length;

先感谢您!

尝试如下在服务中使用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;
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM