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