【问题标题】:Angular 2 - Child routes load parent componentAngular 2 - 子路由加载父组件
【发布时间】:2017-11-20 02:36:19
【问题描述】:

我正在尝试让我的路由在我的 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 生成的。

提前谢谢你。

【问题讨论】:

    标签: angular routing angular-cli


    【解决方案1】:

    组件中不需要另一个<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> 的好处。

    【讨论】:

      【解决方案2】:

      Angular 是一个 SPA(Single Page Application) 平台,所以它会有一个单页分页技术。您需要将<router-outlet> 包含到您的PrivateComponent 中,以让Angular 在那里加载子路由的组件。 Router-outlet 表示子组件的加载位置。

      更多信息请见Defining Child Routes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-06
        • 2018-10-31
        • 2016-12-19
        • 2017-07-02
        • 2018-03-20
        • 2021-05-31
        • 2019-12-02
        相关资源
        最近更新 更多