'How to look for changes in localStorage in Angular 4?
I am trying to access the localStorage using Angular 4 and look for changes in the localStorage values using the Observables:
Here's the code I have been working on:
userNameObservable: Observable<string>;
userName: String = '';
ngOnInit() {
this.userNameObservable = Observable.create(
Observable.of(localStorage.getItem('profileName'))
);
this.userNameObservable.subscribe((name: String) => {
this.userName = name;
})
}
but I am getting an error ERROR TypeError: this._subscribe is not a function. How do I resolve this? Is there a better and efficient way to look for changes in localStorage?
Solution 1:[1]
Find below solution.
Add below code in your ngOnInit or AfterViewInit.
if (window.addEventListener) {
window.addEventListener("storage", this._listener, false);
}
and declare the below function within the class.
private _listener = () => {
// your logic here
}
also remove the listener when you done with listening or ngOnDestroy
window.removeEventListener("storage", this._listener, false);
Cheers.
Solution 2:[2]
We cannot keep a watch on Local Storage using Subject but we can make use of Subject in order to achieve the goals.
for that we'll have to create a subject,
private storageSub = new Subject<string>();
also create a observable,
public storageSubObs: Observable<any>
assign the observable for the Subject,
ngOnInit(): void {
this.storageSubObs = this.storageSub.asObservable();
}
now we have to trigger when the local storage is changed, for that we'll add the code right after the local storage is updated/changed.
localStorage.setItem('item', yourItemData);
this.storageSub.next('changed');
now where we want to know the change status we'll do,
this.storageSubObs..subscribe((data:string) => {
// invokes when the localstorage is changed.
})
thanks & regards
Solution 3:[3]
you can use TypeScript getters to achive this.
get userName() {
return localStorage.getItem('profileName');
}
Solution 4:[4]
If you want to detect events from local storage
window.addEventListener('storage', function(e) {
console.log('event from localstorage')
// any change/trigger in local storage will be catch here
});
// for example you clear the local storage
window.addEventListener('storage', function(e) {
if (localStorage.length === 0) {
console.log('localstorage empty')
}
});
Solution 5:[5]
Observables won't work as local storage can be affected in many ways.
you can attach host listener to local storage as Storage interface emits storage event on global objects which it affects.
something like this
import { KeyboardEvent } from '@angular/core';
@Component({
...
host: {
'(document:storage)': 'onStorageChange($event)'
}
})
export class MyComponent {
onStorageChange(ev:KeyboardEvent) {
// do something meaningful with it
console.log(`Localstorage change/updated!`);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kewin Fernando |
| Solution 2 | |
| Solution 3 | Raed Khalaf |
| Solution 4 | Julian |
| Solution 5 | Sunil Kashyap |
