I'm trying to receive an json Array and store it in the local storage. I've seen some questions like this but they couldn't help me. So i wanted to try with my own question. Im developing in Ionic Framework.
My controller includes following:
app.controller('QuestionsCtrl', function($scope, $http, $stateParams, $localstorage) {
$scope.getData = function() {
// get the json
$http.get("data/fragenArray.json")
.success(function(data) {
//output of json as a string -> correct
console.log('data: ' + JSON.stringify(data));
// store json in local storage
$localstorage.setObject('fragenset', data);
// restore json from local storage
var post = $localstorage.getObject('fragenset');
// output of local storage item -> incorrect
// I got: Test xxx: [object Object]
console.log('Test xxx: ' + post);
})
.error(function(data) {
alert("ERROR");
});
}
});
To store the json I've got:
angular.module('utils', [])
.factory('$localstorage', ['$window', function($window) {
return {
set: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
setObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key) {
return JSON.parse($window.localStorage[key] || '{}');
}
}
}]);
So I decided to try it without the http.get request:
app.run(function($localstorage, $http) {
$localstorage.setObject('post', {"fragen":[
{
"id":"1",
"frage":"Wie ist das Wetter?",
"antworten": {
"a_1":"gut",
"a_2":"schlecht"
}
},
{
"id":"2",
"frage":"Wie geht es dir?",
"antworten": {
"a_1":"gut",
"a_2":"schlecht"
}
}
]});
var post = $localstorage.getObject('post');
console.log(post);
})
And the result ist exactly what i expected - an json object.
So how can i store the json array from the http.get correctly?