Angular 2 - 子路由加载父组件

Ton*_*ler 5 routing angular-cli angular

我试图让我的路由在我的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 },
];
Run Code Online (Sandbox Code Playgroud)

每当我尝试导航到其中一个子路由时,它就会加载父路由.

所以我要说比较一下: -

http://localhost:4200/#/admin

它会引入正确的组件PrivateComponent.

但是当我导航到: -

http://localhost:4200/#/admin/account-settings
Run Code Online (Sandbox Code Playgroud)

或帐户设置任何孩子,它加载了PrivateComponent不和AccountSettingsComponentUserInformationComponent在代码中陈述,你可以在上面看到.

我在代码中遗漏了一些东西以使其工作吗?

该应用程序是使用Angular CLI生成的.

先感谢您.

Sur*_*yan 9

Angular是一个SPA(单页面应用程序)平台,因此它将采用单一分页技术.您需要包含<router-outlet>在您的内容中PrivateComponentAngular加载子路径的组件.Router-outlet显示将加载子组件的位置.

有关更多信息,请参阅定义子路由


sla*_*jma 6

您将不需要<router-outlet>在组件中的另一个。

除了component在父级路由中定义a之外,在子级中还具有指向父级的根路径,如下所示:

{ path: 'admin', children: [
    { path: '', component: PrivateComponent },
    { path: 'account-settings', children: [
        { path: '', component: AccountSettingsComponent},
        { path: 'user-information', component: UserInformationComponent},
        { path: 'companys-information', component: CompanysInformationComponent}
    ] },
] },
Run Code Online (Sandbox Code Playgroud)

另一方面,<router-outlet>如果您想为每个子路径显示一个公共元素(例如标题),我可以看到使用附加元素的好处。