[英]Force angular component to reload on back button press
我有一個 TeamSeasonComponent,它有一個 url 的http://localhost:4200/teams/season/<team_id>
。 在該頁面上,有指向其他團隊的鏈接,這些鏈接將導航到http://localhost:4200/teams/season/team_2_id>
。 我使用 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]) ) }
這一切都按預期工作。 我遇到的問題是,如果我從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()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.