注意LocalStorage angular2中的更改 [英] Watch for changes in LocalStorage angular2

查看:79
本文介绍了注意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天全站免登陆