Watch for changes in LocalStorage angular2

前端 未结 1 1991
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-28 21:15

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 LocalStor

相关标签:
1条回答
  • 2020-12-28 21:35

    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
    })
    
    }
    
    0 讨论(0)
提交回复
热议问题