I am currently building an Angular application where I make a request to an api, and I map the repsonse to two different arrays. I can use this data in my app.components.t
To share information between components you can use a behaviorSubject in a service that will be used in your different components.
The BehaviorSubject has the characteristic that it stores the “current” value, the last value, that needs to be shared with other components.
Its particularity is:
need an initial value
const subject = new MyBehaviorSubject('initialValue');
return the last value of the subject
You can retrieve the last value with getValue() method ( non observable)
subject.getValue()
you can subscribe to it:
subject.subscribe(console.log);
update the value with next()
subject.next('New value');
I give you an example: in my service:
private isOpen = new BehaviorSubject(false);
public getNavBarOpen(): Observable {
return this.isOpen.asObservable();
}
setNavBarOpen(status: boolean): void {
this.isOpen.next(status);
}
in my component:
if I want to update the value :
this.myService.setNavBarOpen(true);
If i want to get the value :
this.myService.getNavBarOpen().subscribe()