typescript - Angular 2 - 替換歷史而不是新增
如何在 Angular 2 的新路由器(rc.1)中用替換歷史的方法,而不是推入新的歷史?
例如,我在問題列表(/questions),在新路由(/questions/add)中打開一個新的模態視窗,並且在添加新問題後,我前往問題檢視(/questions/1)。如果我按返回鍵,我希望返回到 /questions 而不是 /questions/add
答案#1
如果你使用
router.navigate
然後
location.replaceState
使用完全相同的路徑,你可以觸發通常會發生的變化,以及替換歷史記錄。
例如,在你的情況下:
this.router.navigate(['questions/1']);
this.location.replaceState('questions/1');
如果你需要在路由中添加參數,你可以使用以下方式創建位置的網址
router.serializeUrl(router.createUrlTree(/* what you put in your router navigate call */));
在你的例子中:
this.router.navigate(['questions/1', {name:"test"}]);
this.location.replaceState(this.router.serializeUrl(this.router.createUrlTree(['questions/1', {name:"test"}])));
更新
看起來 Angular 路由器現在有一個替換 URL 的選項。在你的範例中:
this.router.navigate(["questions/1"], {replaceUrl:true});
更新 2
目前存在一個問題,即在短時間內進行多次導航可能無法正確替換 URL。作為臨時解決方法,可以將 navigate 函數包裹在一個超時中,以便讓每次導航在不同的週期中執行:
setTimeout(()=>{
this.router.navigate(["questions/1"], {replaceUrl:true});
});
答案#2
你想使用 Locations 類別的 replaceState
https://angular.io/docs/ts/latest/api/common/index/Location-class.html#!#replaceState-anchor
