What does ngStorage's $sync() do?

560 views Asked by At

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?

3

There are 3 answers

2
Ron Newcomb On BEST ANSWER

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.

0
Estus Flask On

As it's said in documentation

changes will be automatically sync'd between $scope.$storage, $localStorage, and localStorage - even across different browser tabs!

As it can be seen here, explicit $sync call updates $storage to be in sync with local/session storage if it isn't for some reason. Usually it shouldn't be called manually, that's why it's not documented.

0
layonez On

From https://github.com/gsklee/ngStorage/blob/master/ngStorage.js

 $sync: function () {
                        for (var i = 0, l = webStorage.length, k; i < l; i++) {
                            // #8, #10: `webStorage.key(i)` may be an empty string (or throw an exception in IE9 if `webStorage` is empty)
                            (k = webStorage.key(i)) && storageKeyPrefix === k.slice(0, prefixLength) && ($storage[k.slice(prefixLength)] = deserializer(webStorage.getItem(k)));
                        }
                    }

As I understand it writes data from inner $storage object to real browser webStorage object and used as private function