2

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?

bmorgs
  • 195
  • 1
  • 12

1 Answers1

6

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.

bmorgs
  • 195
  • 1
  • 12
  • Try not use a `location.reload`: it's better call a funciton initialize or similar. a location.reload, load all the app – Eliseo Apr 06 '21 at 06:59
  • is there any event function like ngOninit which fires when the back button is clicked? – Gajen Dissanayake Feb 28 '22 at 03:17
  • This doesn't trigger in Chrome using Angular 14 for me – Ste Jul 13 '22 at 12:40
  • @Ste you might want to use a listener on ActivatedRoute as described here: https://stackoverflow.com/a/68754029/13497139. Instead of subscribing to params, I've subscibed to the url, and that works great to catch a backpress. – hwgn Jan 20 '23 at 16:30