Reputation: 89
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?
Upvotes: 6
Views: 15451
Reputation: 1
Like others have mentioned you can use localStorage to solve this. I did something similar to this by using the queryParams property of route.
import { ActivatedRoute } from '@angular/router'
routeSubscription!: Subscription
paramData: number //since desired property in url is a number (1234)`
constructor(private route: ActivatedRoute)
{
this.routeSubscription = this.route.queryParams.subscribe(params => {
this.paramData = params.data //params.data holds value 1234
});
}`
After storing the parameters in a variable I called a function with paramData as the argument to load the appropriate data from a post (or get) httpClient
Upvotes: 0
Reputation: 888
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().
Upvotes: 2