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?
Asked
Active
Viewed 1.3k times
1 Answers
28
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
})
}

SeleM
- 9,310
- 5
- 32
- 51

Rohan Fating
- 2,135
- 15
- 24
-
Ultimately this solution is cleaner than mine if you can count on everything that uses localStorage does so through this service. You do have some code issues though. The type of the subject is boolean, but you're passing strings to next(), and since you're passing strings it might as well be the key of the changed item. Also an item may be set that may match what's already in storage so nothing should've changed, but the OP can implement that level of detail if they want. – Daniel Gimenez Sep 06 '17 at 15:24
-
1Thanks a lot. Works perfectly – Hubert Sep 07 '17 at 09:29
-
5But what if user directly change local storage from browser's devTools? – Jagruttam Panchal Feb 06 '19 at 10:22
-
3Should I Unsubscribe in the component? – Jackie Apr 30 '19 at 13:45