保存和獲取該值或許所有其他的答案是角2.X.
現在它不適用於角度5.X.我正在使用它。
只有NavigationEnd,你不能得到以前的網址。
因爲路由器從「NavigationStart」,「RoutesRecognized」,...到「NavigationEnd」工作。
您可以
router.events.forEach((event) => {
console.log(event);
});
檢查,但你仍然不能得到以前的網址,即使「NavigationStart」。
現在你需要使用pairwise。
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/pairwise';
constructor(private router: Router) {
this.router.events
.filter(e => e instanceof RoutesRecognized)
.pairwise()
.subscribe((event: any[]) => {
console.log(event[0].urlAfterRedirects);
});
}
與pairwise,你可以看到什麼網址來自和。
「RoutesRecognized」是從原點到目標網址的變化步驟。
所以過濾它,並從它得到以前的網址。
最後但並非最不重要的,
這段代碼放在父組件或更高(例如,app.component.ts)
因爲這段代碼火災完成佈線後。
謝謝@Günter你總是節省我的一天。 –
這沒有列出我以前的路線,只有當前的路線。 –
取決於你的期望。由於沒有先前的路線,它第一次是「空」。您還需要在根路由器上執行此操作,否則僅當您在此組件的子路由之間導航時纔會獲得。 –