我有一个 TeamSeasonComponent,其 url 为
http://localhost:4200/teams/season/<team_id>
。在该页面上,有其他团队的链接,可以导航至 http://localhost:4200/teams/season/team_2_id>
。我使用一个函数在这两个页面之间进行路由:
export function routeToTeamSeason(team_season_id: string): void{
localStorage.clear()
this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate(['/teams/season', team_season_id])
)
}
这一切都按预期进行。我遇到的问题是,如果我从
team_1's
页面导航到 team_2's
页面,然后按浏览器上的后退按钮,URL 将更新为 team_1's
team_season_id
,但组件不会刷新并且 team_2's
数据仍然显示。如果我刷新页面,它会重新加载 team_1's
数据。
如何在 URL 更改时强制刷新页面?我有一些组件会出现此问题,因此如果我可以制定一些全局规则,在 URL 更改时始终重新加载任何组件,那就太理想了。否则,我如何为特定组件实现这样的规则?
当然我发帖后5分钟就找到答案了。我能够设置一个全局规则,以便在按下后退/前进按钮时重新加载我的组件:
import { HostListener } from '@angular/core';
@HostListener('window:popstate', ['$event'])
onPopState(event) {
location.reload()
}
只需将其放入我的 app.component.ts 中,它的所有子组件现在都会在任何 window:popstate 发生时调用
location.reload()
。
我只是想丰富@bmorgs 的答案。下面在 Angular 15 中进行了测试。像这样使用它,页面仍然感觉像 SPA,而不是在浏览器中进行硬刷新。
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,
});
}