0

My question is quite general. I want to watch for localStorage changes in angular but every key in localStorage need to be watched separately.

For example, I have some products list in localStorage at some key _products_ let's say, which stores an array of products. Now, whenever I add a new product and appending it to the _products_ key in localStorage, I want other components to know _products_ is modified.

A solution is available here but that watches for all the keys in localStorage.

Appreciate your help. Thanks.

2 Answers2

0

You should define localStorage in shared service which is accessible for all you components and to use Subject to track the changes inside localStorage.Hereby an example to use Subject

savinn
  • 68
  • 8
0

use a Subject.

whenever you update your products key, call next() on the subject.

now in any other file, if you wanna watch the changes made to this key,, just subscribe to this subject;

this is the code in the service file where you update the key:

@Injectable()
class KeyService {
  let storageObservable = new Subject<Product>();//use anything you want instead of the Product

  .
  .
  .

  methodWhereYouUdateTheProductKey(){
    //do your things
    //
    //
    this.storageObservable.next(newValueOfKey);
  }

  public followProducstKey(): Oservable<Product> {
    return this.storageObservable;
  }
  
}

and this is the code in to watch the changes in that key:

this.keyService.followProducstKey.subscribe(
  data => {
    console.dir(data);
    //do anything you want with the data you passed on the next() function
  }
);
Fatemeh Majd
  • 719
  • 8
  • 22