angularjsng-storage

What does ngStorage's $sync() do?


ngStorage is a wrapper for the browser's localStorage and sessionStorage objects for AngularJS.

Besides re-exposing the get/set methods, it also provides a $sync() method. But localStorage and sessionStorage reads & writes are already synchronous, so what does the $sync method do?


Solution

  • The angular service accepts objects but browser storage only accepts strings. So it basically uses a proxy object with gettor/settor on it to call JSON.stringify() or JSON.parse() as appropriate.

    Manually calling $sync() and $apply() can be a safety check. Since storage is across browser tabs there's a potential multithread issue. There is a window of time between the user's change happening and the angular digest calling $sync automatically where a change in data from one browser tab can wipe out a change from the other tab that's attempting to alter the same object at the same time.

    But it seems to be one of those only-happens-in-QA-who-is-looking-for-it kinds of issues.