I have a component (properties.component.html) that renders real estate properties. When a user clicks on a specific property, I set a Behavior Subject equal to this property.
private property = new BehaviorSubject<Property>();
setProperty(property) {
this.property.next(property);
}
The component (property.component.html) renders just fine with the data returned from the observable in the service from the Behavior Subject.
this.propertyService.getProperty()
.subscribe((property) => {
this.currentProperty = property;
})
My issue: when the page reloads, the Behavior Subject is now 'empty?' with no data because the .next(property) gets called in properties.component.html on a click.
How can an application hold data on page refresh/reload?
Another poster mentions storing the property in localStorage as a stringified JSON. If that's the solution, then how can a user access this specific property by directly visiting https://www.myapp.com/property/1234?
Not the most elegant solution, but you can do something like this:
@Injectable()
export class PropertyService {
private property = new ReplaySubject<Property>(1);
constructor() {
let storedProp = localStorage.get('storedProp');
if (storedProp)
this.setProperty(JSON.parse(storedProp), false);
}
setProperty(property: Property, storeProp: boolean = false) {
if (storeProp)
localStorage.set('storedProp', JSON.stringify(property));
this.property.next(property);
}
getProperty() {
return this.property;
}
}
The subscriber would get the value whenever it subscribes to proptery through getProperty().subscribe().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With