订阅 Angular 服务中变量值的变化

onm*_*way 1 rxjs typescript angular

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

我已经做了很多搜索,但找不到解决方案(如果有可能的话!)。

我有一个component它是我的布局(标题)的一部分,它显示了购物车中的商品数量。该值绑定到变量simsInCartLength

然后我有一个service处理从购物车中添加和删除项目的操作。在serviceI 中有一个名为的变量noSims,用于存储购物车中项目数组的长度。

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

我的组件中的代码:

simsInCartLength = this.cartService.noSims;
Run Code Online (Sandbox Code Playgroud)

我的服务中的代码(当从购物车中添加或删除项目时,变量会更新:

this.noSims = this.simsInCart.length;
Run Code Online (Sandbox Code Playgroud)

先感谢您!

Sha*_*vek 5

尝试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()


Run Code Online (Sandbox Code Playgroud)

在您的组件中订阅该事件:


ngOnInit(){
  this.cartService.getCartItemCount().subscribe(len => {
     console.log(len) // your new cart length here
     this.simsInCartLength  = len;
  })
}

Run Code Online (Sandbox Code Playgroud)