Retry
Retry

Reputation: 43

Detect local storage changes and show on page without reloading

I have an issue with angular,ionic 4 localstorage.When i save data on localstorage from one page ,and want to show the data to an other page,i need to reload the page to make it work.I thought about checking for localstorage changes in the page i want to show the data.Do you know how can i detect changes in localstorage in angular 7,ionic 4?

Upvotes: 0

Views: 15254

Answers (4)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

You can have a service which takes care of setting and retrieving values to/from localStorage in property setters and getters.

Once the template is bound to properties, your respective components will be updated on change detections.

For example, this is your service with one property you want to set in localStorage.

import { Injectable } from '@angular/core';

@Injectable()
export class SetStorageService {

  private _localItem: string = '';
  constructor() { }

  set localItem(value: string) {
    this._localItem = value;
    localStorage.setItem('localItem', value);
  }

  get localItem() {
    return this._localItem = localStorage.getItem('localItem')
  }

}

And your components like:

export class AppComponent  {
  name = 'Angular';
  private _item: string = ""

  constructor(private _storageService: SetStorageService) {}

  set item(value) {
    this._item = value;
    this._storageService.localItem = value;
  }

  get item() {
    return this._item = this._storageService.localItem;
  }

  addValue() {
    this.item = "New Value"
  }
}

Your view will be bound to the property which is ultimately getting its data from localStorage (through the service).

<p>
  Item in App component - <b>{{item}}</b> 
</p>

See an example here:

https://stackblitz.com/edit/angular-pgdz8e?file=src%2Fapp%2Fapp.component.ts

Upvotes: -2

chrizel
chrizel

Reputation: 52

localStorage.setItem(key, value);
localStorage.getItem(key);

To remove you can use

 ngOnDestroy() {
    localStorage.removeItem('key');
  }

Upvotes: -2

papastepan
papastepan

Reputation: 199

I think you should use rxjs stream to accomplish this.

   private storageSub= new Subject<string>();
  ...

  watchStorage(): Observable<any> {
    return this.storageSub.asObservable();
  }

  setItem(key: string, data: any) {
    localStorage.setItem(key, data);
    this.storageSub.next('added');
  }

  removeItem(key) {
    localStorage.removeItem(key);
    this.storageSub.next('removed');
  }

Upvotes: 5

Daniel Pi&#241;eiro
Daniel Pi&#241;eiro

Reputation: 3149

To check if a value in the storage has changed you can add a listener to the event of the storage like this:

document.addEventListener('storage', (e) => {  
    if(e.key === 'theyKeyYouWant') {
       // Do whatever you want
    }
});

Upvotes: 2

Related Questions