简体   繁体   中英

Go to parent route in Angular 2

Let's say I have a component that creates or edits a thing .

The url for the creation is /things/create and the url for edition is /things/edit/4 . These routes have the same parent.

Once I fill in the form, I call some webservice and then I go back to my previous state which was /things .

How do I tell angular to go back to the parent route?

I could use this.router.navigate(['../'], {relativeTo : this.route}); but ['../'] would only work for /things/create . For /things/edit/4 it would go back to /thing/edit which doesn't exist.

This component is used in two different places, one of which has an extra step before the creation so I can't use back() .

Logic based on the current url

if(router.url.indexOf('create')>= 0){
    this.router.navigate(['../'], {relativeTo : this.route});
 }else {
    this.router.navigate(['../../'], {relativeTo : this.route});
}

so if your current URL path contains the create you know you just have to go back one level, otherwise you go back two levels for the edit.

Use Input to get base URL

Another approach might be to have an @Input for the base URL to go back to. So each component that initializes your component has to pass it the parent url.

{
@Input
parentUrl;

this.router.navigate[parentUrl];
}

您可以使用

this.router.navigate['/things']

So you should be able to check for the id of the thing in the ActivatedRoute params to get the context if the component is creating or editing a component. If there is a param['thingId'] then go to ../../ otherwise go to ../

May be this idea a bit old school but I am sure it will work and is quite simplistic to implement. You can add query param called 'source' and navigate to 'source once the operation is done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM