我需要将json对象存储到angularjs本地存储中。在我的情况下,当从GCM收到推送通知我需要存储到本地存储对象,我需要在一个单独的页面中显示,我通过下面的代码完成了这个
var sessionmessages = [];
var notification = {
"local": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"ldata": {
"Nick": "Mario",
"body": "great match!",
"Room": "PortugalVSDenmark"
}
};
sessionmessages.push(notification);
var notification1 = {
"server": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"sdata": {
"Nick": "Mario",
"body": "great match!",
"Room": "PortugalVSDenmark"
}
};
sessionmessages.push(notification1);
$localstorage.set('mrksesionnotifi', sessionmessages);
console.log($localstorage.getObject('mrksesionnotifi')); // error like Uncaught SyntaxError: Unexpected token o in JSON at position 1
我的工厂如下,
.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] || '{}');
}
}
}])
但是当我将对象数组存储到localstorage中时,我无法取回它,得到的错误就像(Uncaught SyntaxError:位于1的JSON中的意外标记o)。请帮助任何人获得预期的结果。
答案 0 :(得分:0)
var sessionmessages = [];
var notification = {
"local": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"ldata": {
"Nick": "Mario",
"body": "great match!",
"Room": "PortugalVSDenmark"
}
};
sessionmessages.push(notification);
var notification1 = {
"server": "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"sdata": {
"Nick": "Mario",
"body": "great match!",
"Room": "PortugalVSDenmark"
}
};
sessionmessages.push(notification1);
$localstorage.setItem('mrksesionnotifi', sessionmessages);
console.log($localstorage.getItem('mrksesionnotifi'));
试试这段代码