How do I share data between sibling components in angular?

Viewed 48110

I have an Angular application with 3 sibling components, they are able to access and update the variable "data". They are connected to the router, but the data I want to pass is sensitive (api endpoints to determine discounts) so I cannot use cmp2/:data

Component 1 has an object called data and Components 2 and 3 need to receive this data object. I think this can be done with a shared service, but I'm not quite sure how to get this event emitter to work..

My index.html:

<router-outlet></router-outlet>

Component 1:

<button [routerLink]=['cmp2/']>Go to Comp 2 </button>
<button [routerLink]=['cmp3/']>Go to Comp 3 </button>

Components 2 and 3:

{{ data }}
4 Answers

Since you have asked to share the data between sibling components we can achieve it by using BehaviourSubject in service.

The BehaviorSubject holds the value that needs to be shared with other components. These components subscribe to data which is simple returning the BehaviorSubject value without the functionality to change the value.

Service.ts

import { Observable, BehaviorSubject } from 'rxjs';

export class Service {
       private data = new BehaviorSubject("")
       currentData = this.data.asObservable();

 constructor() { }

 setData(data) {
      this.data.next(data);
 }

Component1.ts

import { Service } from '../service.service';

export class component1 implements OnInit {

data: any;

constructor (private service: Service) {}

sendDataToService() {
     this.service.setData(this.data);
}

Component2.ts

import { Service } from '../../service.service';

export class component2 implements OnInit {

constructor ( private service: Service ) { }

ngOnInit() {
    this.service.currentData.subscribe(data => {
      console.log(data);
    });
}
Related