Angular ngStorage 自定义对象
Angular ngStorage Custom Objects
我正在使用 ngStorage 来存储数据。我制作了一个名为游戏的自定义对象并将其存储。它作为游戏存储,但当我刷新浏览器时,它作为对象返回。
var games= $localStorage.games || {};
this.addGame = function(){
var newGame = new game("Game "+games.length);
$localStorage.games = newGame;
}
var game = function(title){
var title=title;
var player1;
var player2;
this.getTitle = function(){
return title;
}
this.setTitle = function(title){
this.title = title;
}
this.getPlayer1 = function(){
return player1;
}
this.setPlayer1 = function(player1){
this.player1 = player1;
}
this.getPlayer2 = function(){
return player2;
}
this.setPlayer1 = function(player1){
this.player2 = player2;
}
}
添加新游戏时,它会作为游戏存储在 LocalStorage 中,但是当我刷新 bowser 并尝试获取游戏时。它 returns 作为对象数组而不是游戏。
您不能在 localStorage 中存储对象。技巧是您可以像这样存储字符串和 parse/unparse 它们。
var game = {
name: 'Super Metroid',
text: 'This is an awesome game!!!'
};
window.localStorage['game'] = JSON.stringify(game);
var superMetroid = JSON.parse(window.localStorage['game'] || '{}');
我正在使用 ngStorage 来存储数据。我制作了一个名为游戏的自定义对象并将其存储。它作为游戏存储,但当我刷新浏览器时,它作为对象返回。
var games= $localStorage.games || {};
this.addGame = function(){
var newGame = new game("Game "+games.length);
$localStorage.games = newGame;
}
var game = function(title){
var title=title;
var player1;
var player2;
this.getTitle = function(){
return title;
}
this.setTitle = function(title){
this.title = title;
}
this.getPlayer1 = function(){
return player1;
}
this.setPlayer1 = function(player1){
this.player1 = player1;
}
this.getPlayer2 = function(){
return player2;
}
this.setPlayer1 = function(player1){
this.player2 = player2;
}
}
添加新游戏时,它会作为游戏存储在 LocalStorage 中,但是当我刷新 bowser 并尝试获取游戏时。它 returns 作为对象数组而不是游戏。
您不能在 localStorage 中存储对象。技巧是您可以像这样存储字符串和 parse/unparse 它们。
var game = {
name: 'Super Metroid',
text: 'This is an awesome game!!!'
};
window.localStorage['game'] = JSON.stringify(game);
var superMetroid = JSON.parse(window.localStorage['game'] || '{}');