2016-11-26 204 views
2

當使用loadChildren()調用導入子路由時,我遇到了覆蓋根路由的問題。Angular2子模塊的forChild()路由覆蓋根路由

應用路線聲明:

const routes: Routes = [ 
    { path: '', redirectTo: 'own', pathMatch: 'full' }, 
    { path: 'own', component: OwnComponent }, 
    { path: 'nested', loadChildren:() => NestedModule}, 
]; 
export const routing = RouterModule.forRoot(routes); 

嵌套子模塊的路線:

const routes: Routes = [ 
    { path: 'page1', component: NestedPage1Component }, 
    { path: 'page2', component: NestedPage2Component }, 
    { path: '', redirectTo: 'page1', pathMatch: 'full' }, 
]; 

@NgModule({ 
    imports: [RouterModule.forChild(routes)], 
    exports: [RouterModule] 
}) 
export class Module1RoutingModule {} 

我可以/自己,/嵌套/第1頁,/嵌套/第2頁,但是當我試圖讓根/ - 我正在重定向到/ page1。爲什麼會發生這種情況,因爲它是在RouterModule.forChild的子模塊中聲明的,它如何不重定向到/ own?

我創建簡單的普拉克攝製 - https://plnkr.co/edit/8FE7C5JyiqjRZZvCCxXB?p=preview

是否有人經歷了這種行爲?

+0

對於其他人來說,[這個github問題](https://github.com/angular/angular/issues/10958)討論了這種路由行爲。 – makman99

回答

4

這是你的分叉和修改plunker:https://plnkr.co/edit/XilkY55WXle2hFF0Pelx?p=preview

不要導入延遲加載的模塊,並改變root的路線是這樣的:

//import { Module1Module } from "./module1/module1.module"; // do NOT import it ! 

export const routes: Routes = [ 
    { path: '', redirectTo: 'own', pathMatch: 'full' }, 
    { path: 'own', component: OwnComponent }, 
    { path: 'module1', loadChildren: 'src/module1/module1.module#Module1Module' }, 
]; 

和嵌套的路線:

const routes: Routes = [ 
    //{ path: 'page1', component: Module1Page1Component }, 
    //{ path: 'page2', component: Module1Page2Component }, 
    //{ path: '', redirectTo: 'page1', pathMatch: 'full' }, 

    // do the routes like this.. 
    { 
    path: '', 
    component: Module1Component, 
    children: [ 
     { path: '', redirectTo: 'page1', pathMatch: 'full' }, 
     { path: 'page1', component: Module1Page1Component }, 
     { path: 'page2', component: Module1Page2Component } 
    ] 
    }, 
]; 
+0

謝謝,它適用於延遲加載。我基本上嘗試了同樣的解決方案,但偶爾也沒有刪除導入的子模塊,因此路由被覆蓋。但問題是一般來說,如果不使用延遲加載 - 路由子路由不應該破壞根路由?這不應該是一個錯誤嗎? – ykravch

+0

我會說它屬於正在導入模塊的順序.. – mxii

+1

好點。你可以在App Module中導入延遲加載的模塊。否則,路線會混淆。 – marekozw