2017-06-17 123 views
0

我想讓我的路由在我的Angular 2應用程序中工作。Angular 2 - 兒童路由加載父組件

這裏是我使用的app.routes.ts文件

export const ROUTES: Routes = [ 
    { path: '',  component: PublicComponent, data: { title: 'Heroes List' } }, 
    { path: 'home', component: PublicComponent }, 
    { path: 'admin', component: PrivateComponent, children: [ 
    { path: '', component: PrivateComponent }, 
    { path: 'account-settings', component: AccountSettingsComponent, children: [ 
     { path: '', component: UserInformationComponent}, 
     { path: 'user-information', component: UserInformationComponent}, 
     { path: 'companys-information', component: CompanysInformationComponent} 
    ] }, 
    ] }, 
    { path: '**', component: NoContentComponent }, 
]; 

每次我嘗試瀏覽到它加載了父路由的子路由的一個代碼。

因此,可以說比如我去: -

http://localhost:4200/#/admin

它拉動正確的組件PrivateComponent。

但是,當我瀏覽到: -

http://localhost:4200/#/admin/account-settings 

或帳戶設置任何兒童作爲你可以看到上面的代碼表示它加載了PrivateComponent而不是AccountSettingsComponentUserInformationComponent

我是否在代碼中丟失了某些東西來使其工作?

該應用程序是使用Angular CLI生成的。

預先感謝您。

回答

2

Angular是SPA(單頁應用程序)平臺,因此它將具備單頁尋呼技術。您需要在您的PrivateComponent中包含<router-outlet>以讓Angular加載子路由組件。 Router-outlet顯示子組件將被加載的位置。

更多看到Defining Child Routes

+0

謝謝,我會接受一旦它讓我。 –

0

你不會需要另一個<router-outlet>在組件中。

而不是在父路由定義component有兒童指向家長,像這樣一個根路徑:

{ path: 'admin', children: [ 
    { path: '', component: PrivateComponent }, 
    { path: 'account-settings', children: [ 
     { path: '', component: AccountSettingsComponent}, 
     { path: 'user-information', component: UserInformationComponent}, 
     { path: 'companys-information', component: CompanysInformationComponent} 
    ] }, 
] }, 

在另一方面,我可以看到使用附加<router-outlet>如果受益你想爲每個子路徑顯示一個通用元素,即標題。