Angular 2 - replace history instead of pushing

我的未来我决定 提交于 2019-11-28 05:18:43

If you use

router.navigate

And then

location.replaceState

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

For example, in your case:

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 */));

In your example:

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

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});
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!