Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch for changes in LocalStorage angular2

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?

like image 796
Hubert Avatar asked Sep 06 '17 15:09

Hubert


1 Answers

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

}
like image 50
Rohan Fating Avatar answered Oct 22 '22 18:10

Rohan Fating