2017-08-02 90 views
0

Plunker:https://plnkr.co/edit/GyUApIPQzTvp9vIahYdT?p=preview如何在Angular中使用子路由延遲加載錯誤路由?

我有路線設置這樣的app.module

const routes = [ 
    { 
    path: '', 
    component: DummyComponent 
    }, 

    { 
    path: '', // is this right? 
    component: SingleComponent, 
    children: [ 
     { 
     path: '**', // is this right? 
     loadChildren: 'src/lazy/lazy.module#LazyModule' 
     } 
    ] 
    } 
]; 

而且在lazy.module我有

const routes = [ 
    { 
    path: '**', // is this right? 
    component: LazyComponent 
    } 
]; 

的問題是,SingleComponent(頁面模板)的實際加載,但頁面內容(LazyComponent)未加載。 (點擊notfound鏈接查看Plunker的結果)

我應該如何配置這個以便SingleComponent(模板)和LazyComponent(內容)加載正確顯示頁面?

注意:此LazyComponent被認爲是一個錯誤頁面,所以我要趕你在做什麼這裏調用/虛擬和/ NOTFOUND路線的所有路由(/notfound/invalid-url/<anything that doesn't exist in router>

+0

你應該在你的應用程序的頂層添加你的'path:'**''route綁定到你的錯誤組件,a最後的路線。這意味着如果在這個匹配器之前沒有發現任何東西,你會得到這條路徑(這是你想要的一個未找到的頁面)。 – Supamiu

回答

1

<a routerLink="/dummy">dummy</a> 
<a routerLink="/notfound">notfound</a> 

而在您的路線定義中,您尚未定義這些路線。你可能會想要做的是:如果你把一個空的路線

const routes = [ 
    { path: '', redirectTo: '/dummy', pathMatch: 'full' }, 
    { 
    path: 'dummy', 
    component: DummyComponent 
    }, 

    { 
    path: 'notfound', 
    component: SingleComponent, 
    children: [ 
     { 
     path: '', 
     loadChildren: 'src/lazy/lazy.module#LazyModule' 
     } 
    ] 
    } 
]; 

第一行會重定向到虛擬路徑。你也不需要的是這個特定情況下的**通配符。

我希望這有助於我瞭解您的問題。

+0

那麼,這是有效的,但這個'notfound'只是一個不存在的路線的例子。我想渲染這個懶惰的組件,以防用戶轉到不存在的頁面。 – BrunoLM

0

我發現了一個辦法做到這一點,不足之處是,它改變的網址:

應用途徑:

const routes = [ 
    { 
    path: '', 
    component: DummyComponent 
    }, 

    { 
    path: '', 
    component: SingleComponent, 
    children: [ 
     { 
     path: 'error', 
     loadChildren: 'src/lazy/lazy.module#LazyModule' 
     } 
    ] 
    }, 

    { path: '**', redirectTo: 'error' }, 
]; 

懶人路線:

const routes = [ 
    { 
    path: '**', 
    component: LazyComponent 
    } 
]; 

Plunker https://plnkr.co/edit/xktoV02EoGjPNwrW2VjR?p=preview

相關問題