本文介绍了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) 中在新路线 (/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"}])));

更新

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

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 - 替换历史而不是推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 12:15