本文介绍了Angular 2-替换历史而不是推送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to replace a history instead a pushing a new in angular 2's new router (rc.1)?

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

For example Im in a question list (/questions) opening a new modal in a new route (/questions/add), and after adding a new question I go to the question view (/questions/1). If I press back I would like to go to the /questions instead of /questions/add

推荐答案

如果使用

router.navigate

然后

location.replaceState

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

With the exact same path, you can trigger changes that usually happen, as well as replacing the history.

例如,在您的情况下:

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

如果需要在路线中添加参数,则可以使用以下方式创建位置的网址

If you need to add parameters to the route, you can create the url for location using

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"}])));

更新

似乎角路由器现在带有替换网址选项.在您的示例中:

Update

It seems the angular router now comes with a replace url option. In your example:

this.router.navigate(["questions/1"], {replaceUrl:true});

更新2

当前有一个问题,其中可能会在很短的时间内完成多次导航不能正确替换URL.作为临时的解决方法,请将导航功能包装在超时中,以使每个功能在单独的周期中触发:

Update 2

There is a current issue where multiple navigations done in a short amount of time may not replace the URL correctly. As a temporary workaround, wrap the navigate function in a timeout to get each to fire in a separate cycle:

setTimeout(()=>{
    this.router.navigate(["questions/1"], {replaceUrl:true});
});

这篇关于Angular 2-替换历史而不是推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:29