Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - Angular 2 - replace history instead of pushing

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...