Search code examples
javascriptangularstore

Angular 2 refresh views on local storage's value change


I have a navbar that prints out the name and the surname of the user. Both these variables are taken from the local storage on component init. I have a modal, in the modal I can change the name and surname of the logged user and put them again in the local storage. If I change them successfully I want to update the navbar with the new name and surname.

The modal and the navbar are two different components.

How can I achieve this?

Solution 1: I was thinking to modify manually the variables while the post of the new data (name and surname) has been successfully executed. Can I modify the variables of another component (the navbar) from the modal?

Solution 2: call a location.reload to force updating automatically all the view with the new data in local storage.

Solution 3: using a store

Thanks


Solution

  • Create a wrapper service for getting/setting local storage, that will also emit when setting. Modal calls, say, this.storageService.setItem('foo', 'bar'), while nav bar has subscribed this.storageService.changes$.

    While there is an event emitted when something writes to the storage, it only get emitted in other windows for the same domain.