【发布时间】:2015-01-30 00:03:31
【问题描述】:
我正在尝试接收一个 json 数组并将其存储在本地存储中。 我见过一些这样的问题,但他们无法帮助我。所以我想尝试我自己的问题。我在 Ionic 框架中开发。
我的控制器包括以下内容:
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");
});
}
});
存储我得到的 json:
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] || '{}');
}
}
}]);
所以我决定在没有 http.get 请求的情况下尝试一下:
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);
})
结果正是我所期望的——一个 json 对象。
那么如何正确存储来自 http.get 的 json 数组呢?
【问题讨论】:
标签: javascript arrays json local-storage ionic-framework