2016-11-08 100 views
6

我的孩子模块路线如下网址参数冲突,角2路线与其他路线

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

要前往这些路线如下,

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

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

但角检测new路线作为:id并导航到TripDetailComponent

这里的问题是Angular为:id路由检测到'new'字符串作为url参数。

我可以添加一个前缀到:id,即view/:id并使这项工作。但是,我需要保持url模式。有没有办法做到这一点?

我的预期URL模式,

/trips  --> show all trips 
/trips/2334 --> show details of trip 2334 
/trips/new --> show a form to create a new trip 

回答

6

目前您的:id路由也与new匹配,并且路由器没有进一步寻找其他匹配路由。

订单是相关的。在:id路由前移动new路由,然后new路由与:id路由前相匹配。

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

感谢Günter。有用。从来没有想过订单会很重要。 –

+1

路线顺序总是让我:|感谢澄清这一点。 – moeabdol

1

不能有图有完全相同的段作为参数的两个路径(:ID路径相匹配)。

但是,您可以使用以下配置手动映射正确的操作。

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

到组件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 
     () => {} 
    ); 

This answer与此相关。

+0

谢谢Nicolas。这比Günter的解决方案有点复杂。但我相信我可能会遇到在应用程序增长时需要使用此方法加载组件的情况。 –