Search code examples
angularrxjsangular2-servicesbehaviorsubject

How to keep behavior subject data on page reload


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?


Solution

  • 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().