Let's say I have 3 angular components:
The issue I am facing:
Whenever I create a new project or update a project, it gets updated in the backend immediately and angular returns from ProjectsFormComponent
to ProjectsComponent
, but the data it shows is outdated. It does not reflect the newly added project. I have to either refresh the page or switch to another component and back to ProjectsComponent
to reflect the changes. The same goes for ProjectUpdateFormComponent
.
Things I have tried in vain:
app-routing.module.ts
@NgModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})], // forces auto-refresh of current URL with real-time data
exports: [RouterModule]
})
ProjectsFormComponent
// Force-refresh of data from the back-end
refresh(): void {
window.location.reload();
}
addProject(): void {
this.projectService.newProject(this.project).subscribe(data => {
alert("Project: " + this.project.name + " has been created successfully!");
this.refresh();
this.router.navigate(['/projects']);
})
}
ProjectComponent
constructor(private router: Router, private projectService: ProjectService, private http: HttpClient) {
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
How do I tell angular to always reload specific pages such as ProjectsComponent
always from the backend instead of fetching old data from its cache?
Modify your refresh method to call a service to fetch the data from the server. In the same way you are adding a new project.
refresh() {
this._projectService.getProjects().subscribe(data => this.projects = data);
}
OR
Have the backend return the updated data when you add a new one and then subscribe to the response.
addProject() {
this._projectService.addProject(project).subscribe(data => this.projects = data)
}
If you are able to switch back to the component to refetch the data, your answer probably lies there. How are you getting it (maybe within ngOnInit?) if so pull this out of the ngOnInit and put it in its own function. Then you can call this in multiple places and reuse it on component initialisation and when you add a new project.