bmorgs
bmorgs

Reputation: 245

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?

Upvotes: 4

Views: 9373

Answers (2)

Akk3d1s
Akk3d1s

Reputation: 236

I would just like to enrich @bmorgs answer. Tested below in Angular 15. Using it like this the page will still feel like an SPA instead of doing a hard refresh in the browser.

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

constructor(private router: Router) {}

@HostListener('window:popstate', ['$event'])
onPopState(event) {
  this.router.navigateByUrl(`${window.location.pathname}`, {
    onSameUrlNavigation: 'reload',
    skipLocationChange: true,
  });
}

Upvotes: 2

bmorgs
bmorgs

Reputation: 245

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.

Upvotes: 7

Related Questions