簡體   English   中英

Angular 2 - 子路由加載父組件

[英]Angular 2 - Child routes load parent component

我試圖讓我的路由在我的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都會加載PrivateComponent而不是您在上面看到的代碼中所述的AccountSettingsComponentUserInformationComponent

我在代碼中遺漏了一些東西以使其工作嗎?

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

先感謝您。

Angular是一個SPA(單頁面應用程序)平台,因此它將采用單一分頁技術。 您需要在您的PrivateComponent加入<router-outlet> ,讓Angular在那里加載子路由的組件。 Router-outlet顯示將加載子組件的位置。

有關更多信息,請參閱定義子路由

您不需要在組件中使用另一個<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>的好處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM