gsklee / ngStorage

localStorage and sessionStorage done right for AngularJS.
MIT License
2.33k stars 461 forks source link

Use before bootstrapping and in app doesn't really work #203

Open Bubelbub opened 8 years ago

Bubelbub commented 8 years ago

My workflow is the following. (function () { 'use strict';

    angular.module('ConfigurationService', []).factory('ConfigurationService', ConfigurationService);

    ConfigurationService.$inject = ['$q', '$localStorage'];

    function ConfigurationService($q, $localStorage) {
        var
            service = {},
            storage = $localStorage.$default({
                configuration: [],
                configuration_ttl: new Date().toJSON()
            })
        ;

        service.initialize = function(clearStorage) {
            var $deferred = $q.defer();
            if(typeof(clearStorage) === 'undefined' || !clearStorage) {
                $.get('configuration.json').done(function(config) {
                    storage.configuration = config;
                    $deferred.resolve();
                }).fail(function(err) {
                    $deferred.reject(err);
                });
            }
            return $deferred;
        });

        return service;
    }

    angular.element(document).ready(function () {
        var
            initInjector = angular.injector(['ng', 'ngStorage' 'ConfigurationService']),
            $localStorage = initInjector.get('$localStorage'),
            ConfigurationService = initInjector.get('ConfigurationService'),
            storage = $localStorage.$default({
                configuration: [],
                configuration_ttl: new Date().toJSON()
            })
        ;

        if (storage.configuration.length > 0 && new Date(storage.configuration_ttl) >= new Date()) {
            ConfigurationService.initialize().then(function () { angular.bootstrap(document, ['app']); });
        } else {
            ConfigurationService.initialize(true).then(function () { angular.bootstrap(document, ['app']); });
        }
    });
})();

And I (try to) save the configuration by:

$localStorage.$apply();

But the storage isn't "synced".

Do you know how I can handle this storage "global"?

egilkh commented 8 years ago

If you really need to use the localStorage before bootstrap of Angular, can't you use windows.localStorage/sessionStrorage instead?

DzmVasileusky commented 6 years ago

The same issue. My intentions are to use angular.injector out of angular inside basic class. Methods of this basic class using some app services, which using $localStorage. But $localStorage doesn't seem to work that way. And It's not a great solution to change all the $localStorage calls to optional window.localStorage.