Search code examples
javascriptarraysangularjslocal-storageangular-local-storage

Persisting array data locally in AngularJS app to be shared between two applications


I have some array data var queries = []; that I want to be persisted and shared between two AngularJS application. 2 applications meaning one for the front end and second for the admin end. Both the ends make the whole page load for when they are loaded.

I tried using the following code for sharing the data but it doesn't seem to work:

.factory('QueryService', function() {
        var queries = [];
        var factory = {};
        //..
    factory.addQuery = function(query) {
          queries.push(query);
        localStorage.setItem('queries', JSON.stringify(queries));
        console.log(JSON.parse(localStorage.getItem('queries')));
        return JSON.parse(localStorage.getItem('queries'));
    };
    //..
    return factory;
}

I only get the last element added to the queries array with the above code.

I also tried the following using the angular-local-storage but I still get the same result.

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

I need the array queries data to be available in the front end app and also in the admin end.

Could somebody help me with it?


Solution

  • Use the factory to setup private variables for the specific factory that you can then set and fetch the value of that private variable.

    You could create another method to clear the queries variable too if necessary.

        .factory('QueryService', function () {
            var queries = [];
            var factory = {};
    
            return {
                addQuery : function (query) {
                    queries.push(query);
                    localStorage.setItem('queries', JSON.stringify(queries));
                    console.log(JSON.parse(localStorage.getItem('queries')));
                    return JSON.parse(localStorage.getItem('queries'));
                },
                fetchQuery : function ( ) {
                    return localStorage.getItem('queries');
                }
            };
        });