Not entirely clear on what you mean by setting and retrieving the value on any page. Are you referring to a component perhaps?
If so, I would recommend using a service like this
@Injectable({
providedIn: 'root'
})
export class ExampleService{
private _value: any;
private _valueObs$ = new BehaviorSubject(null);
set setValue(newValue: any): void{
this._value = newValue;
}
get getNewValue(): any{
return this._value;
}
set setObservableValue(newValue: any): void{
this._valueObs$.next(newValue)
}
get getNewObservableValue(): any{
return this._valueObs$;
}
}
The method above demonstrates two approaches; the first being a standard set and get, while the second utilizes a Subject. The difference between the two will be discussed in the following section.
To implement this service in any component:
@Component({
selector: 'example',
})
export class ExampleComponent implements OnInit {
newValue: any;
constructor(private readonly exampleService: ExampleService
) { }
ngOnInit(): void {
this.getObservableExampleValue();
}
getExampleServiceValue(): any {
this.exampleService.getNewValue;
}
setExampleServiceNewValue(value: any): void {
this.exampleService.setNewValue = value;
}
getObservableExampleValue() {
this.exampleService.getNewObservableValue.subscribe((newObsValue) => {
this.newValue = newObsValue
})
}
setObservableExampleValue(value: any): void{
this.exampleService.setObservableValue(value);
}
ngOnDestroy(){
this.exampleService.getNewObservableValue.unsubscribe();
}
}
No need to delve into the details of setValue & getNewValue; feel free to use them as needed.
The second approach is particularly useful if you want multiple components to be aware of a specific value simultaneously. For instance, setting the _valueObs$
with the setObservableValue
method will notify all 5 components using this service about that value – quite handy, isn't it?
Remember to invoke getNewObservableValue
to open the stream and make the value accessible for your component's template/code, typically done during ngOnInit
. Subscribing to observables works akin to turning on a tap.
Imagine turning on a tap – that's subscribing
this.exampleService.getNewObservableValue.subscribe((newObsValue) => {
this.newValue = newObsValue
})
The tap is now running, emitting a stream of water (or data here); thus, every time a new value is set, it flows through the stream updating this.newValue
in your component automatically.
However, remember to turn off the tap when not needed to avoid wastage – unsubscribe when the component is no longer active
ngOnDestroy(){
this.exampleService.getNewObservableValue.unsubscribe();
}
This prevents memory leaks, which are beyond this scope of discussion. For more on Rxjs, consider reading documentation at https://www.learnrxjs.io/ or watch tutorials on YouTube. Feel free to comment if further clarification is needed.