【问题标题】:Force angular component to reload on back button press强制角度组件在按下后退按钮时重新加载
【发布时间】:2021-07-01 21:11:02
【问题描述】:

我有一个 URL 为 http://localhost:4200/teams/season/<team_id> 的 TeamSeasonComponent。在该页面上,有指向其他团队的链接,这些链接将导航到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'steam_season_id,但组件不会刷新并且@ 987654328@ 数据仍然显示。如果我然后刷新页面,它会重新加载 team_1's 数据。

如何在 URL 更改时强制刷新页面?我有几个组件会遇到这个问题,所以如果我可以制定一些全局规则,如果 URL 发生更改,总是重新加载任何组件,那将是理想的。否则,我怎样才能为特定组件实施这样的规则?

【问题讨论】:

    标签: angular routes back


    【解决方案1】:

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

    import { HostListener } from '@angular/core';
    
    @HostListener('window:popstate', ['$event'])
    onPopState(event) {
      location.reload()
    }

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

    【讨论】:

    • 尽量不要使用location.reload:最好调用函数初始化或类似的。一个location.reload,加载所有应用
    猜你喜欢
    • 2012-02-22
    • 2015-05-20
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 2023-03-03
    • 2015-07-15
    • 2016-03-18
    • 2014-02-17
    相关资源
    最近更新 更多