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
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);
});
}