I have been trying to find the best solution to share some data beetween two componentes that share the same parent.
I am using an angular-material stepper. Step 1 has one component and step 2 has another one. What i am trying to do is to "click" 1 button in the component from the step 1 and refresh an array of data that affects component in step 2.
This is my code:
Global service:
export class GlobalDataService {
private reserveSource = new BehaviorSubject<any[]>([]);
currentReserve = this.reserveSource.asObservable();
constructor() { }
changeReserve(reserve: any[]) {
this.reserveSource.next(reserve)
}
}
Component 1 that tries to update:
setSpace(id) {
this.apiObservableService
.getService('http://localhost:8080/Spaces/' + id)
.subscribe(
result => {
this.space = result;
this.globaldataservice.changeReserve(result.reserves);
sessionStorage.setItem('currentSpace', JSON.stringify(result));
},
error => console.log(error)
);
}
Component 2 that tries to read and refresh:
ngOnInit(): void {
this.currentUser = JSON.parse(sessionStorage.getItem('currentUser'));
this.currentSpace = JSON.parse(sessionStorage.getItem('currentSpace'));
this.globaldataservice.currentReserve.subscribe(message => this.reserves = message)
console.log(this.reserves);
}