首页 > 解决方案 > 标头共享组件上的购物车数量未从 Angular 10 中的另一个组件更新

问题描述

我想要没有。当我单击“添加到购物车”按钮时,标题组件上的购物车图标上的项目数量会增加。但只有当我刷新页面时,这同样有效。

我正在使用购物车服务来存储全局数据,然后在标题组件上访问相同的数据。我确实订阅了初始化时的主题行为。请看一下这些代码片段:

我的 cart.service.ts 文件:

export class CartService {
  public cartItem: ICartItem[] = [];
  cartItems = new BehaviorSubject<ICartItem[]>(this.cartItem);
  cartItems$ = this.cartItems.asObservable();

  constructor(private cookieService: CookieService) {
    this.GetCartData()
  }

  GetCartData() {
    if (this.cookieService.check('cartItems')) {
      this.cartItem = JSON.parse(this.cookieService.get('cartItems'));
    } else {
      this.cartItem = [];
    }
    this.cartItems.next(this.cartItem);
  }

  publishCartChange() {
    this.cartItem = JSON.parse(this.cookieService.get('cartItems'));
    this.cartItems.next(this.cartItem);
  }

  AddCartItem(item: ICartItem) {
    this.cartItem.push(item);
    this.cookieService.set('cartItems', JSON.stringify(this.cartItem));
    this.cartItems.next(this.cartItem);
  }
}

我如何在标题组件上访问它:

this.cartService.publishCartChange();
    this.cartItemSub = this.cartService.cartItems$.subscribe(res => {
      console.log(res);
      this.cartItems = res;
      console.log(res);
      this.cartQty = this.cartItems.length;
    }); 

这就是我的“添加到购物车”按钮的作用:

addtoCart() {
    let cartItem: ICartItem = {'ItemId': this.product['itemId'], 'ItemName': this.product['itemName'], price: this.product['specialPrice'], 'qty': this.qty, 'amount': this.product['specialPrice']* this.qty };
    this.cartService.AddCartItem(cartItem);
  }

标签: angularangular-servicesangular10

解决方案


您是否添加了可注入属性,并指定将其注册到根注入器?这将使它成为一个应用程序范围的单例,这可能是您想要的。

providers如果你已经通过模块/组件注册了它,请确保从任何 NgModule/Component 的数组中删除它。

@Injectable({ providedIn: 'root' })
export class CartService {
 ...
}

推荐阅读