Reputation: 785
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?
Upvotes: 7
Views: 20786
Reputation: 1771
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')
}
});
Upvotes: 1
Reputation: 1622
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
Upvotes: 1
Reputation: 2984
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!`);
}
}
Upvotes: -2
Reputation: 320
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.
Upvotes: 14
Reputation: 2065
you can use TypeScript getters to achive this.
get userName() {
return localStorage.getItem('profileName');
}
Upvotes: 0