我有一个关于 Angular 的小问题。
我在一个组件中有一个按钮,当按下它时,它会选择一个游戏并运行一个函数,该函数只是将游戏发送到一个名为 SelectedGameService 的服务,这样我就可以了解选择了哪个游戏.这是我的代码;
games.component.html中的按钮;
<a class="btn btn-primary" (click)="handleDetails(game)" style="position: absolute; top:86%; background-color: #0909CD;" routerLink="/games/game-details/{{game.title}}">See The Game Details</a>
正如我所说,handleDetails(game) 函数将游戏发送到该函数。 game.component.ts 中的 handleDetails 函数是;
handlePrice(game) {
this.selectedGameService.selectedGame = game;
}
该函数将游戏发送到 selectedGameService。这是我在该服务中的代码;
import { Injectable } from '@angular/core';
import { Games } from '../games/Games';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class SelectedGameService {
selectedGame: Games;
constructor(private http: HttpClient) {
this.selectedGame = new Games;
}
基本上,此服务会创建一个新游戏,并将其等同于触发 handlePrice(game) 函数的游戏。
这是我的问题。当我运行代码时,它在浏览器中完美运行。当我按下“查看游戏详情”按钮时,我可以看到我想要的页面,但是当我在该页面刷新浏览器时,游戏的所有信息都消失了。我该如何解决这个问题?
您可以看到我在该页面刷新浏览器时的前后图片。
从现在开始谢谢你。
最佳答案
如果刷新浏览器,服务中变量中存储的数据将被清除。解决这个问题的一种方法是使用 session 或本地存储来存储数据:
handleDetails(value) {
localStorage.setItem('key', value);
}
从本地存储中检索数据:
localStorage.getItem('key');
关于angularjs - Angular ,页面刷新时数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62834093/