Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force angular component to reload on back button press

I have a TeamSeasonComponent which has a url of http://localhost:4200/teams/season/<team_id>. On that page, there are links to other team's which would navigate to http://localhost:4200/teams/season/team_2_id>. I route between those two pages using a function:

export function routeToTeamSeason(team_season_id: string): void{
    localStorage.clear()
    this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
        this.router.navigate(['/teams/season', team_season_id])
    )
}

This all works as expected. The issue I'm having is if I navigate from team_1's page to team_2's page, and then press the back button on my browser, the URL updates with team_1's team_season_id, but the component does not refresh and team_2's data is still displayed. If I then refresh the page, it reloads with team_1's data.

How can I force a page refresh any time the URL changes? I have a few components that will have this issue, so if I can make some global rule that always reloads any component if the URL changes, that would be ideal. Otherwise, how can I implement a rule like that for a specific component?

like image 593
bmorgs Avatar asked Sep 19 '25 10:09

bmorgs


1 Answers

Of course I find an answer 5 minutes after posting. I was able to set a global rule to reload my a component any time a back/forward button gets pressed with this:

import { HostListener } from '@angular/core';

@HostListener('window:popstate', ['$event'])
onPopState(event) {
  location.reload()
}

Just had to put that in my app.component.ts, and all it's children components will now call a location.reload() any time a window:popstate occurs.

like image 100
bmorgs Avatar answered Sep 22 '25 08:09

bmorgs