angular - 标头共享组件上的购物车数量未从 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);
}
解决方案
您是否添加了可注入属性,并指定将其注册到根注入器?这将使它成为一个应用程序范围的单例,这可能是您想要的。
providers
如果你已经通过模块/组件注册了它,请确保从任何 NgModule/Component 的数组中删除它。
@Injectable({ providedIn: 'root' })
export class CartService {
...
}
推荐阅读
- c++ - std::filesystem::directory_iterator 真的是迭代器吗?
- nativescript-vue - 未显示底部导航图标
- powershell - 在 PowerShell 中将哈希表导出到 CSV 中的多个列
- azure - 在 Azure 中为 Kubernetes 配置两个环境
- reactjs - 如何编写需要两行的 React Styled Component 属性?
- pdf - Grails wkhtmltopdf 插件。导出为 pdf 时不显示图像
- java - Google Ads API:使用服务帐号访问
- bash - 使用同一个程序在 bash 中运行多行
- javascript - 三.js / OrbitControls 未定义
- trace32 - TRACE32:练习脚本:迭代变量列表