2016-11-08 98 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的解決方案有點複雜。但我相信我可能會遇到在應用程序增長時需要使用此方法加載組件的情況。 –