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

时间:2021-04-06 04:17:04

标签: angular routes back

我有一个 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 更改时总是重新加载任何组件,那将是理想的。否则,我如何为特定组件实现这样的规则?

1 个答案:

答案 0 :(得分:0)

当然,我在发帖 5 分钟后找到了答案。我能够设置一个全局规则来在按下后退/前进按钮时重新加载我的组件:

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

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

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