-1

我想将数据存储在本地存储中,以便在页面刷新时不会丢失它。

我的 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 存储在本地存储中。但我想我犯了一个编码算法错误。因为当我刷新页面时,我仍然会丢失数据(不是来自本地存储,而是来自页面本身)。如果你能帮助我,我会很高兴。

4

1 回答 1

0

尝试这个。

 ngOnInit() {
    if (localStorage.getItem('theGame')) {
      this.selectedGame = JSON.parse(localStorage.getItem('theGame')); // use existing localstorage value
    } else {
      this.setGame(value);    // set your new game value
    }

  }

setGame(game: Games) {
   const tempGame = JSON.stringify(game);
   if (!localStorage.getItem('theGame') || (tempGame !== localStorage.getItem('theGame'))) {
       localStorage.setItem('theGame', tempGame);
       this.selectedGame = game; 
}
  }

注意:如果 localstorage 没有针对 'theGame' 的任何值或已保存的值与当前传递的值不同,请将当前值设置为 localstorage。否则只使用 this.selectedGame 的当前值。

于 2020-07-11T16:47:41.483 回答