zoomsphere / ngx-store

Angular decorators to automagically keep variables in HTML5 LocalStorage, SessionStorage, cookies; injectable services for managing and listening to data changes and a bit more.
https://www.npmjs.com/package/ngx-store
ISC License
167 stars 41 forks source link

Can't track changes made to store from external sources #53

Closed ghost closed 5 years ago

ghost commented 6 years ago

For my current project there is need to pass data from a non angular control to angular. The primary application is made with Angular-Cli and thus AoT, we have client side plugins and orchestration that makes use of the web storage facility.

I have been trying to make the ng app respond to changes in the local storage.

This my configuration:

    var NGXSTORE_CONFIG = {
        prefix: 'ngx_',
        clearType: 'prefix',
        mutateObjects: true,
        debugMode: true,
        cookiesScope: '',   
        cookiesCheckInterval: 250
    };

This is my listener (set up in the init routine of app main):

    this.LocalStorageService.observe("test_key",true).subscribe(
      result => {
        console.log("test key was triggered")
        console.log(result)
      },
      error => {
        console.log(error)
      },
      () => {
        console.log("tried reading from store")
      }
    )

from an external js file, I implement the following on a click event:

function InjectTestEvent(value, id) {
    var testEvent = {
        Value: value,
        Id: id    
    }
    localStorage.setItem('ngx_test_key', JSON.stringify(testEvent))
}

When invoked, InjectTestEvent creates or updates the local storage item with key ngx_test_key as intended, but this is ignored on the LocalStorageService.

To make sure the key actually exists beforehand (and to confirm the name), I created it ahead of the subscription with

this.LocalStorageService.set("test_key", "")

The same result is achieved, I can update, set and remove this key by name from inside angular, but any change to the stored key externally is ignored.

Am I doing something wrong?

ghost commented 6 years ago

I've managed to achieve what I wanted with a basic workaround.

I extended the localStorage.setItem function in my external js file:

var baseSetItem = localStorage.setItem;

localStorage.setItem = function () {
    window.dispatchEvent(new StorageEvent('storage', { key: arguments[0], newValue: arguments[1] }));
    baseSetItem.apply(this, arguments);
};

and replaced the subscription @ LocalStorageService with an old fashioned listener

window.addEventListener("storage", event => { console.log(event) }, false)