简体   繁体   English

在Angular 5中的两组同级组件之间共享数据

[英]Sharing data between two sets of sibling components in Angular 5

Pretty new to Angular. Angular的新手。 Came from mobile app development. 来自移动应用程序开发。

I know there are so much information teaching how to share data between sibling components. 我知道有太多信息可以教教如何在同级组件之间共享数据。 But my question is sharing data between 2 sets of sibling components. 但是我的问题是在2组同级组件之间共享数据。

So code-wise, I have 2 components (A and B). 因此从代码角度来说,我有2个组件(A和B)。 When a button in A is clicked, B is updated. 单击A中的按钮时,B将更新。 But UI-wise, there are 2 sets of this AB components. 但是在UI方面,有2套此AB组件。 So when a button in A1 is clicked, B1 is updated. 因此,当单击A1中的按钮时,将更新B1。 When a button in A2 is clicked, B2 is updated. 单击A2中的按钮时,将更新B2。

How can I achieve this? 我该如何实现?

What I have tried 我尝试过的

In the first place, I used a service to share data. 首先,我使用了一项服务来共享数据。 But then found that when A1 was clicked, both B1 and B2 were updated, which is what I don't want. 但是随后发现,单击A1时,B1和B2均被更新,这是我不想要的。 Same for A2 was clicked. 单击与A2相同。

Using a service to share data between two sibling components is definitely the best way of doing it, the only thing you need to do here is add a key to your components. 使用服务在两个同级组件之间共享数据绝对是最好的方式,这里唯一需要做的就是向组件添加密钥。

<comp-a [key]="1"></comp-a>
<comp-b [key]="1"></comp-b>
<comp-a [key]="2"></comp-a>
<comp-b [key]="2"></comp-b>

If the components are generated via a *ngFor , you could use the index of the loop or perhaps an object id if one is getting bound. 如果组件是通过*ngFor生成的,则可以使用循环的索引,或者如果绑定一个对象,则可以使用对象ID。

Anyway, when comp-a calls the service, you should include the key. 无论如何,当comp-a调用服务时,您应该包括密钥。 When the event that comp-b is listening to gets fired, you should include the key in the event and comp-b should only respond to it if it matches its own key. comp-b正在侦听的事件被触发时,您应在该事件中包括该键,并且comp-b仅在匹配其自己的键时才对其做出响应。

I think you provided your service at module level and that's why you have single instance. 我认为您在模块级别提供了服务,这就是为什么您只有一个实例。

Provide your service at component level. 在组件级别提供服务。 Create a wrapper component which holds Both A and B and provide the service at this component level. 创建一个同时包含A和B的包装器组件,并在此组件级别提供服务。 Each time the wrapper component is created a new instance of service will be created and that instance will be available only to A and B. 每次创建包装器组件时,都会创建一个新的服务实例,并且该实例仅对A和B可用。

@Component({
    selector: 'app-abwrapper',
    templateUrl: './abwrapper.component.html',
    styleUrls: ['./abwrapper.component.scss'],
    providers: [{
        MyServiceToShareData
    }]
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM