首页 文章

如何在页面重新加载时保持行为主题数据

提问于
浏览
3

我有一个组件(properties.component.html)呈现房地产属性 . 当用户单击特定属性时,我将行为主题设置为等于此属性 .

private property = new BehaviorSubject<Property>();

setProperty(property) {
  this.property.next(property);
}

组件(property.component.html)使用行为主题从服务中的observable返回的数据可以很好地呈现 .

this.propertyService.getProperty()
  .subscribe((property) => {
     this.currentProperty = property;
  })

我的问题:当页面重新加载时,行为主题现在是“空的”?没有数据,因为点击时在properties.component.html中调用.next(属性) .

应用程序如何在页面刷新/重新加载时保存数据?

另一张海报提到将localStorage中的属性存储为字符串化的JSON . 如果这是解决方案,那么用户如何通过直接访问https://www.myapp.com/property/1234来访问此特定属性?

1 回答

  • 1

    不是最优雅的解决方案,但您可以这样做:

    @Injectable()
    export class PropertyService {
    
        private property = new ReplaySubject<Property>(1);
    
        constructor() {
            let storedProp = localStorage.get('storedProp');
            if (storedProp)
                setProperty(JSON.parse(storedProp), false);
        }
    
        setProperty(property: Property, storeProp: boolean = flse) {
            if (storeProp)
                localStorage.set('storedProp', JSON.stringify(property);
            this.property.next(property);
        }
    
        getProperty() {
            return this.property;
        }
    }
    

    只要订阅者通过getProperty() . subscribe()订阅proptery,订阅者就会获得该值 .

相关问题