0

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?

4

2 回答 2

1

使用工厂为特定工厂设置私有变量,然后您可以设置并获取该私有变量的值。

如有必要,您也可以创建另一种方法来清除查询变量。

    .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');
            }
        };
    });
于 2014-10-06T18:03:30.167 回答
1

你应该试试这个:

// save to localStorage
localStorage.myData = angular.toJson(data);


// retrieve from localStorage
var data = angular.fromJson(localStorage.myData);

让我知道这个是否奏效。

于 2014-10-06T17:49:30.953 回答