Search code examples
javascriptarraysangularjslocal-storageangular-local-storage

Storing elements in an array in Local Storage using Angular Local Storage Module


I just need to store an array in localStorage and keep adding elements to that array so I could retrieve that stored array in my application. This must be a very simple thing to do with Angular Local Storage Module but it has got me troubling quite a bit, and I am hoping to get some help on this.

Following is the angular code I have that I am using to store a queries into localStorage using angular-local-storage module:

.factory('QueryService', ['localStorageService', function(localStorageService) {
        var queries = [];
        var factory = {};

        factory.addQuery = function(query) {
            queries.push(query);

            localStorageService.set('queries', queries);
            return localStorageService.get("queries");
        };
        return factory;
    }])

Every time I add a query to the queries array, I get only the last element added returned in the result. So basically, localStorageService.get("queries") is giving me the last element added to the queries array.

Could somebody please help me understand that why am I getting only the last element I am adding to the queries array returned?

EDIT: After each element I am adding to the queries array I am refreshing the browser.


Solution

  • Normally you can not store arrays directly with localStorage. But angular-local-storage does this work for you as seen on this line: https://github.com/grevory/angular-local-storage/blob/ed422c04764d4981a48f4c40859d65087b1b9838/src/angular-local-storage.js#L119

    The clue to answer your question is that you are refreshing your browser after adding an element, so the queries array does indeed get cleaned up. A browser refresh actually wipes out all of your JavaScript values and the controller even your whole AngularJS application gets restarted.

    To make your code work you have to initialize the queries array in the first line of your controller:

    .factory('QueryService', ['localStorageService', function(localStorageService) {
            var queries = localStorageService.get('queries') || [];
            var factory = {};
    
            factory.addQuery = function(query) {
                queries.push(query);
    
                localStorageService.set('queries', queries);
                return localStorageService.get("queries");
            };
            return factory;
        }])