我想将数据存储在本地存储中,以便在页面刷新时不会丢失它。
我的 html 文件中有一个按钮可以从 typescript 文件中触发此函数(该函数有一个名为“game”的参数,这是我创建的一个类);
handlePrice(game) {
//HERE I CALL THE FUNCTION SETGAME OF GAMESERVICE
this.selectedGameService.setGame(game);
}
大家可以看到,这个函数从 selectedGameService 中调用了另一个名为 setGame 的函数。这是该服务的代码;
export class SelectedGameService {
selectedGame: Games; //SELECTEDGAME IS AN ELEMENT FROM GAMES CLASS
constructor(private http: HttpClient) { }
setGame(game: Games) {
//FIST, I CHECK IF THE KEY 'theGame' IS EMPTY OR NOT AT LOCAL STORAGE
if(localStorage.getItem('theGame') === null) {
//IF THE KEY IS EMPTY, I SET SELECTEDGAME AS THE NEW INCOMING GAME
//AND STORE THE GAME AT LOCAL STORAGE WITH THE KEY 'theGame'
this.selectedGame = game;
localStorage.setItem('theGame', JSON.stringify(this.selectedGame));
}
else {
//IF THERE IS AN EXISTING GAME IN LOCAL STORAGE ALREADY
//I SET THE SELECTEDGAME AS THE GAME IN THE KEY 'theGame'
this.selectedGame = JSON.parse(localStorage.getItem('theGame'));
}
}
}
正如我从 F12 的应用程序部分检查的那样,我可以将 selectedGame 存储在本地存储中。但我想我犯了一个编码算法错误。因为当我刷新页面时,我仍然会丢失数据(不是来自本地存储,而是来自页面本身)。如果你能帮助我,我会很高兴。