Watch for changes in LocalStorage angular2

2020-03-01 20:39发布

问题:

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?

回答1:

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

}