I have a little question in Angular.
I have a button in a component that when pressed, selects a game and runs a function and that function just sends the game to a service called SelectedGameService, so that I can understand which game was selected. Here are my codes;
The button in 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>
As I have said, the handleDetails(game) function sends the game to that function. That handleDetails function in game.component.ts is;
handleDetails(game) {
this.selectedGameService.selectedGame = game;
}
That function send the game to selectedGameService. here are my codes in that service;
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;
}
So basically this service creates a new game and equals it to the game that triggered the handlePrice(game) function.
Here is my problem. When I run the code, it runs perfectly in browser. When I press "See The Game Details" button I can see the page as I want, but when I refresh the browser while at that page, all the information of the game disappears. How can I solve this problem?
You can see the before and after pictures of when I refresh the browser while at that page.
Thank you from now.
Before Refreshing The Page
After Refreshing The Page
Data stored in variables in services will be cleared if the browser is refreshed . One way to solve this is by using session or local storage to store the data:
handleDetails(value) {
localStorage.setItem('key', value);
}
To retrieve data from local storage:
localStorage.getItem('key');
The data which you store in a service resides in the memory. When you refresh the page, the browser frees up the memory and give your app a clean slate to write on.
If you want to maintain state across page refreshes you should go for localStorage for saving your data.
The process you should follow is:
You can read up about localStorage from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With