通过共享服务在两个组件之间进行角度2/4通信 [英] Angular 2/4 communication between two component via a shared service

查看:59
本文介绍了通过共享服务在两个组件之间进行角度2/4通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个简单的购物车应用程序. 我有两个组件和一个购物车服务,如下所示.

I am trying to build a simple shopping cart application. I have two components and a cart service like following.

<app-header></app-header>

<app-cart></app-cart> 

购物车服务具有用于将商品添加到购物车,删除购物车中的商品,购物车数量等所有功能.

In cart service has all the functionality for doing adding an item to cart, delete item in the cart, cart quantity etc.

当用户将产品添加到购物车时,我需要更新标题组件中的购物车计数.

I need to update the cart count in the header component when the user adds a product to the cart.

如何使用共享服务.

推荐答案

在这种情况下,您可以将服务与 subject 一起使用. Angular中的服务是单例,这意味着将其作为单个实例进行管理.因此,如果每个组件都访问该服务,它们将访问相同的共享数据.

In this case, You can use a service with subject. A service in Angular is a singleton, meaning it is managed as a single instance. So if each of the components access the service, they will access the same shared data.

export class cartService{
    private prodCount = 0;
    prodCountCountChange: Subject<number> = new Subject<number>();
    UpdateCount(count: number) {
        this.prodCount = count;
        this.prodCountCountChange.next(this.prodCount);
    }
}

您可以在组件中执行此操作

In your component you can do this,

  this._cartService.UpdateCount(this.prod.length);

这篇关于通过共享服务在两个组件之间进行角度2/4通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆