按下后退按钮时强制角度组件重新加载

bmo*_*rgs 4 routes back angular

我有一个 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])
    )
}
Run Code Online (Sandbox Code Playgroud)

这一切都按预期进行。我遇到的问题是,如果我从team_1's一个页面导航到另一个team_2's页面,然后按浏览器上的后退按钮,URL 会更新为team_1's team_season_id,但组件不会刷新并且team_2's数据仍然显示。如果我刷新页面,它会重新加载team_1's数据。

如何在 URL 更改时强制刷新页面?我有一些组件会出现此问题,因此如果我可以制定一些全局规则,在 URL 更改时始终重新加载任何组件,那就太理想了。否则,我如何为特定组件实施这样的规则?

bmo*_*rgs 6

当然,我在发布后 5 分钟就找到了答案。我可以设置一个全局规则,以便在按下后退/前进按钮时重新加载组件:

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

@HostListener('window:popstate', ['$event'])
onPopState(event) {
  location.reload()
}
Run Code Online (Sandbox Code Playgroud)

只需将其放入我的 app.component.ts 中,它的所有子组件现在都会在location.reload()发生 window:popstate 时调用 a 。