6

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?

starlight
  • 765
  • 3
  • 14
  • 30

5 Answers5

10

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.

Kewin Fernando
  • 260
  • 4
  • 18
1

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

AMAL MOHAN N
  • 1,416
  • 2
  • 14
  • 26
1

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')
  }
});
Julian
  • 886
  • 10
  • 21
U.Aasd
  • 1,396
  • 1
  • 8
  • 11
0

you can use TypeScript getters to achive this.

get userName() {
   return localStorage.getItem('profileName');
}
Raed Khalaf
  • 1,997
  • 2
  • 13
  • 29
  • 1
    This seems to work, but is not able to detect if any changes are done to localStorage values – starlight Aug 09 '17 at 11:41
  • if you change the localStorage values manually, of course it will not detect the changed, but the changes on the local storage must done programmatic ally, in this case it will detect it. – Raed Khalaf Aug 09 '17 at 11:43
  • I tried this with a list of 100 objects, the application ran very slow. its unsafe for larger arrays. – Gour Gopal Dec 24 '22 at 13:06
-1

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!`);
  }
}
Sunil Kashyap
  • 2,946
  • 2
  • 15
  • 31