观察 LocalStorage angular2 的变化

Watch for changes in LocalStorage angular2

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

你要的是主题。在此处查看文档 (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
})

}