[英]Angular 2 route with url parameter conflicts with other routes
My child module routes are as follows, 我的子模块路由如下,
{
path: '',
children: [
{ path: '', component: TripManagerComponent },
{ path: ':id', component: TripDetailComponent },
{ path: 'new', component: TripNewComponent }
]
}
I am navigating to these routes as follows, 我按照以下方式导航到这些路线,
navigateToTrip(index: number) {
this.router.navigate([index], { relativeTo: this.route });
}
navigateToNewTrip() {
this.router.navigate(['new'], { relativeTo: this.route });
}
But Angular detects new
route as :id
and navigates me to TripDetailComponent
. 但是Angular
TripDetailComponent
new
路由检测为:id
并将我导航到TripDetailComponent
。
The problem here is Angular detects 'new' string as url parameter for :id
route. 这里的问题是Angular将'new'字符串检测为url参数
:id
route。
I could add a prefix to :id
, ie view/:id
and make this work. 我可以添加一个前缀
:id
,即view/:id
并使其工作。 But, I need to keep the url pattern as it is. 但是,我需要保持url模式不变。 Is there a way to do this?
有没有办法做到这一点?
My expected url pattern is, 我期望的网址模式是,
/trips --> show all trips
/trips/2334 --> show details of trip 2334
/trips/new --> show a form to create a new trip
Currently you :id
route matches also with new
and the router doesn't look further for other matching routes. 目前您
:id
路由也与new
匹配,路由器不会进一步寻找其他匹配路由。
The order is relevant. 订单是相关的。 Move the
new
route before the :id
route, then the new
route matches before the :id
route. 在
:id
路由之前移动new
路由,然后new
路由在:id
路由之前匹配。
{
path: '',
children: [
{ path: '', component: TripManagerComponent },
{ path: 'new', component: TripNewComponent }
{ path: ':id', component: TripDetailComponent },
]
}
You cannot map two path with the same exact segments as parameter ( :id matches the new path). 您不能使用与参数相同的精确段映射两个路径( :id匹配新路径)。
However, you can map manually the correct action with the following configuration. 但是,您可以使用以下配置手动映射正确的操作。
{
path: '',
children: [
{ path: '', component: TripManagerComponent },
{ path: ':id', component: TripDetailComponent },
]
}
Into the component TripDetailComponent
, you can trigger the creation process if the parameter is equal to new. 如果参数等于new,则可以在组件
TripDetailComponent
中触发创建过程。
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
() => {}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.