Angular 2——替换历史记录而不是推送



如何在angular 2的新路由器(rc.1)中替换历史,而不是推送一个新的?

例如,我在一个问题列表(/questions)中打开一个新路由(/questions/add)的新模态,在添加一个新问题后,我进入问题视图(/questions/1)。如果我按回键,我想转到/questions而不是/questions/add

如果使用

router.navigate

location.replaceState

使用相同的路径,您可以触发通常发生的更改,以及替换历史记录。

例如:

this.router.navigate(['questions/1']);
this.location.replaceState('questions/1');

如果需要在路由中添加参数,可以使用

为location创建url
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 h1> 前存在一个问题,即在短时间内完成多个导航可能无法正确替换URL。作为临时解决方案,将导航函数包装在超时中,以使每个函数在单独的循环中触发:
setTimeout(()=>{
    this.router.navigate(["questions/1"], {replaceUrl:true});
});

您需要使用来自Locations类的replaceState

https://angular.io/docs/ts/latest/api/common/index/Location-class.html !# replaceState-anchor

最新更新