注意LocalStorage angular2的变化

时间:2017-09-06 15:06:35

标签: angular local-storage angular2-template

我在LocalStorage和ngOnInit钩子中存储了一些对象,我将这些数据接收到我在模板中显示* ngFor的数组。如何查看LocalStorage中的更改并自动更新视图?

1 个答案:

答案 0 :(得分:15)

你想要的是一个主题。查看此处的文档(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<boolean>();
  ...

  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
})

}