观察 LocalStorage angular2 的变化 [英] Watch for changes in LocalStorage angular2

查看:21
本文介绍了观察 LocalStorage angular2 的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 LocalStorage 和 ngOnInit 钩子中存储了一些对象,我将此数据接收到我使用 *ngFor 显示在模板中的数组中.如何观察 LocalStorage 中的变化并自动更新视图?

I stored some objects in LocalStorage and in ngOnInit hook I receive this data to the array which I display in template with *ngFor. How can I watch for changes in LocalStorage and automatically update the view?

推荐答案

你想要的是一个主题.在此处查看文档(https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md)

What you want is a Subject. Check out the docs here (https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md)

For a quick example, something like this:
    @Injectable()
export class StorageService {
  ...
  private storageSub= new Subject<String>();
  ...

  watchStorage(): Observable<any> {
    return this.storageSub.asObservable();
  }

  setItem(key: string, data: any) {
    localStorage.setItem(key, data);
    this.storageSub.next('changed');
  }

  removeItem(key) {
    localStorage.removeItem(key);
    this.storageSub.next('changed');
  }
}

Inside Component

constructor(private storageService: StorageService  ){}
ngOnInit() {
this.storageService.watchStorage().subscribe((data:string) => {
// this will call whenever your localStorage data changes
// use localStorage code here and set your data here for ngFor
})

}

这篇关于观察 LocalStorage angular2 的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆