I have been struggling to find an effective way to share data between two components that have the same parent in an Angular application.
Currently, I am working with an Angular Material stepper where Step 1 contains one component and Step 2 contains another component. My goal is to trigger an action by clicking a button in the Step 1 component that will update an array of data used by the Step 2 component.
Here is a snippet of my code:
Global service:
export class GlobalDataService {
private dataSubject = new BehaviorSubject<any[]>([]);
currentData = this.dataSubject.asObservable();
constructor() { }
changeData(newData: any[]) {
this.dataSubject.next(newData);
}
}
Component 1 responsible for updating the data:
updateData(id) {
this.apiObservableService
.getService('http://localhost:8080/Spaces/' + id)
.subscribe(
result => {
this.space = result;
this.globaldataservice.changeData(result.reserves);
sessionStorage.setItem('currentSpace', JSON.stringify(result));
},
error => console.log(error)
);
}
Component 2 which reads and refreshes the data:
ngOnInit(): void {
this.currentUser = JSON.parse(sessionStorage.getItem('currentUser'));
this.currentSpace = JSON.parse(sessionStorage.getItem('currentSpace'));
this.globaldataservice.currentData.subscribe(data => this.reserves = data)
console.log(this.reserves);
}