angularjs - Angular ,页面刷新时数据丢失

标签 angularjs angular typescript

我有一个关于 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) 函数的游戏。

这是我的问题。当我运行代码时,它在浏览器中完美运行。当我按下“查看游戏详情”按钮时,我可以看到我想要的页面,但是当我在该页面刷新浏览器时,游戏的所有信息都消失了。我该如何解决这个问题?

您可以看到我在该页面刷新浏览器时的前后图片。

从现在开始谢谢你。

Before Refreshing The Page

After Refreshing The Page

最佳答案

如果刷新浏览器,服务中变量中存储的数据将被清除。解决这个问题的一种方法是使用 session 或本地存储来存储数据:

    handleDetails(value) {
      localStorage.setItem('key', value);
      }

从本地存储中检索数据:

localStorage.getItem('key');

关于angularjs - Angular ,页面刷新时数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62834093/

相关文章:

javascript - Angular 中断了 jQuery 幻灯片放映

javascript - Angular Js : Scope Arrays

javascript - ngx-bootstrap for angular - datepicker 如何在似乎没有任何效果时更改主题颜色

javascript - 如何从 Protractor 网络驱动程序获取文本字段值

javascript - Angular 4专注于向下箭头上的元素并滚动

angular - textarea中的maxlength在Angular中不起作用

javascript - Angular 过滤器可在应用过滤器之前从输入的单词中删除重音符号

Angular 2 路由器 - 使用 angularfire2 解析身份验证

javascript - 找不到路线/发布/添加

javascript - 无法编写基本的 Controller AngularJS