Reputation: 71
I have this basic app where I grab data from a firestore with a data service. I have several pages(components), teams, players, statistics...
for instance my team component:
import { Component, OnInit } from '@angular/core';
import { TeamsService } from '../../services/teams.service';
import { Team } from '../../models/team';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'app-teams',
templateUrl: './teams.component.html',
styleUrls: ['./teams.component.css']
})
export class TeamsComponent implements OnInit {
public teams: Team[];
editState: boolean = false;
teamToEdit: Team;
showAdd: boolean = false;
showSelect: boolean = false;
selectedTeam: Observable<Team>;
constructor(public teamsService: TeamsService) {
}
ngOnInit() {
this.teamsService.getTeams().subscribe(teams => {
this.teams = teams;
console.log('ngOnInit invoked');
});
}
deleteTeam(event, team) {
const response = confirm('are you sure you want to delete?');
if (response) {
this.teamsService.deleteTeam(team);
}
return;
}
editTeam(event, team) {
this.editState = !this.editState;
this.teamToEdit = team;
}
updateTeam(team) {
this.teamsService.updateTeam(team);
this.teamToEdit = null;
this.editState = false;
}
showAddForm() {
this.showAdd = !this.showAdd;
}
getTeam(event, team) {
this.showSelect = !this.showSelect;
this.selectedTeam = this.teamsService.getTeamById(team.id);
}
}
In the ngOnInit I load my data into the local variables, but once i navigate away to another page and then come back the data is gone. I literally need to refresh the page to reload the data.
How should I solve this?
Upvotes: 1
Views: 1094
Reputation: 12378
Create a resolver guard and use it in your route configuration for TeamsComponent. Also, create a service that will do the data retrieval and inject it into the resolver. This service can either make a new request for data each time the user navigates to this route or cache the data and provide them to your TeamComponent on each subsequent visit of the route.
Take a look at this sample app that illustrates the general use of the resolver guard: https://github.com/Farata/angulartypescript/tree/master/code-samples/chapter4/router-advanced-samples/src/app/resolver.
But if you want to implement an injectable service with cache, take a look at the code in data.resolver2.ts and data.service.ts.
Upvotes: 1