假设,我的电子商务网站有两个组件。 Header组件和Cart组件。标题组件包含一个图标,该图标与一个值相关,该值表示添加到购物车中的商品总数。同时,购物车组件包含许多物品。每个单个项目都由另一个Item组件表示,该组件包含相应的图像,计数器,价格和数量。我想做的是,每当增加每件物品的数量时,它也应该增加购物车图标的值,该值在标题上。我该怎么办?
Header Component
export class HeaderComponent implements OnInit {
cart_item = 0; /* Variable that increases cart item value on header */
ngOnInit() {}
}
项目组件
export class ItemComponent implements OnInit {
@Input() line_item: any; /* From the Cart Component */
ngOnInit() {}
/* Function that increases the quantity of item */
incrementQuantity() {
this.line_item.quantity++;
}
}
在这种情况下,您可以将服务与主题一起使用。 Angular中的服务是单例,这意味着将其作为单个实例进行管理。因此,如果每个组件都访问该服务,则它们将访问相同的共享数据。
export class cartService{
private cart_item = 0;
prodCountCountChange: Subject<number> = new Subject<number>();
UpdateCount(count: number) {
this.cart_item = count;
this.prodCountCountChange.next(this.prodCount);
}
}
您可以在组件中执行此操作,
this._cartService.UpdateCount(newCount);