gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:14:50 28 4
gpt4 key购买 nike

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

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

我有一个 component,它是我的布局(标题)的一部分,它显示了购物车中的商品数量。此值绑定(bind)到变量 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;
})
}

关于angular - 订阅 Angular 服务中变量值的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57900977/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com