2016-07-31 44 views
2

是否可以使用children配置「終端」路線,或者換句話說,具有「可選」children的路線。使用可選子項創建路線

我想創建一個可路由的主/細節視圖,其中的細節最初不顯示,並且當詳細視圖打開時,列表不會被銷燬。

例如,導航至/a,然後在不破壞a的情況下導航至/a/1

首次嘗試

const routes: RouterConfig = [ 
    //... 
    { path: 'a', component: AListComponent, children: [ 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
    //... 
]; 

...這個配置,下面的錯誤被拋出:

EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: 'a'

第二次嘗試

const routes: RouterConfig = [ 
    //... 
    { path: 'a', component: AListComponent }, 
    { path: 'a', component: AListComponent, children: [ 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
    //... 
]; 

...列表組件被銷燬並重新創建,即如果它具有用戶輸入,則值將消失。

第三次嘗試 - 創建一個「Empty」組件並默認加載它。

const routes: RouterConfig = [ 
    //... 
    { path: 'a', component: AListComponent, children: [ 
    { path: '', component: EmptyComponent }, 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
    //... 
]; 

...作品,但感覺像一個解決方法。

有沒有更好的方法?

+0

如何使用不顯示任何「可選」路由的虛擬組件? AFAIK你正在尋找什麼不被支持。 –

+1

@GünterZöchbauer,感謝您的評論。你的建議基本上是我的第三次嘗試 - 它有效,但並不「感覺正確」。但是,如果您將您的評論作爲答案,我很樂意接受它。這種方法如何看待你?英雄之旅(https://angular.io/docs/ts/latest/tutorial/toh-pt2.html)使用* ngIf來實現這一點,但使用路由器感覺好一點。如果空分量方法看起來不太可怕,那麼至少在目前這可能是一種前進的方式。 –

+0

恕我直言,如果'ngIf'非常合適,主要取決於您是否想在URL中反映狀態。如果這不是'ngIf'沒有必要或有用的話,那應該沒問題。 –

回答

1

在我看來,最好的方法是在第三次嘗試時不顯示任何內容的空虛擬組件。

+0

謝謝!我希望這在未來的版本中變得更簡單。 –

3

你的第三個嘗試的一個更簡單的版本是簡單地用一個空路徑與任何東西的,甚至不是一個組件:

const routes: Routes = [ 
    { path: 'a', component: AListComponent, children: [ 
    { path: '' }, 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
]; 

維克多Savkin有written about componentless routes,雖然他並沒有走得這麼遠至於使用這樣的完全空路線(他的例子包含redirectchildren屬性)。

根據您的設置,您甚至可以更進一步並刪除/a路徑。我有一個功能模塊中的routes聲明這樣,延遲加載path: 'module-path'下:

const routes: Routes = [ 
    { path: '', component: AListComponent, children: [ 
    { path: '' }, 
    { path: ':id', component: ADetailsComponent } 
    ]}, 
]; 

所以路由到/module-path負載AListComponent其中包含一個空<router-outlet>,和路由/module-path/5填充與ADetailsComponent出口。

+0

謝謝您的建議!這看起來像一個改進。 –