Angular 2 route with url parameter conflicts with other routes

My child module paths are as follows:

{ path: '', children: [ { path: '', component: TripManagerComponent }, { path: ':id', component: TripDetailComponent }, { path: 'new', component: TripNewComponent } ] } 

I navigate these routes as follows:

 navigateToTrip(index: number) { this.router.navigate([index], { relativeTo: this.route }); } navigateToNewTrip() { this.router.navigate(['new'], { relativeTo: this.route }); } 

But Angular defines the new route as :id and takes me to TripDetailComponent .

The problem here is Angular defines a new line as the url parameter for the route :id .

I could add a prefix to :id , i.e. view/:id and do the job. But I need to save the url template as is. Is there any way to do this?

My expected url pattern,

 /trips --> show all trips /trips/2334 --> show details of trip 2334 /trips/new --> show a form to create a new trip 
+6
source share
2 answers

Currently, you :id mapping the route to new , and the router is no longer looking for other suitable routes.

Order matters. Move the new route to the route :id , then the new route will match before the route :id .

 { path: '', children: [ { path: '', component: TripManagerComponent }, { path: 'new', component: TripNewComponent } { path: ':id', component: TripDetailComponent }, ] } 
+6
source

You cannot map two paths to the exact same segments as the parameter (: id matches the new path).

However, you can manually map the correct action to the following configuration.

 { path: '', children: [ { path: '', component: TripManagerComponent }, { path: ':id', component: TripDetailComponent }, ] } 

In the TripDetailComponent component TripDetailComponent you can initiate the creation process if the parameter is equal to the new one.

 this.route.params.subscribe( params => { let id = params['id']; if (id === "new") { // Create a new element } else if(p.match(/\d+/)){ // Display the details } else { // Handle when id is not a number } }, // Handle error err => this.logger.error(err), //Complete () => {} ); 

This answer is related to this.

+1
source

Source: https://habr.com/ru/post/1012150/


All Articles