在同一路由器出口中加载嵌套路由

问题描述 投票:0回答:2

我有一个 Angular 4 应用程序和我的

private.component.html
类似这样的东西:

<app-breadcrumb></app-breadcrumb>
<router-outlet></router-outlet>

我的路线:

const privateRoutes: Routes = [
    {
        path: '',
        component: PrivateComponent,
        children: [
            {
                path: 'dashboard',
                component: DashboardComponent
            },
            {
                path: 'settings',
                component: SettingsComponent
            },
            {
                path: 'companies',
                component: CompaniesComponent,
                children: [
                    {
                        path: 'add',
                        component: FormCompanyComponent
                    },
                    {
                        path: ':id',
                        component: CompanyComponent
                    }
                ]
            }
        ]
    }
];

第一层的所有组件都在PrivateComponent

router-outlet
中渲染。但我希望(如果可能的话)所有其他子级(并且我可以有多个级别),例如
/companies/add
/companies/20
仍然在我的私有模板的同一个 router-outlet 中呈现。当然,我的实际代码希望我的插座位于
companies.component.html
内。

这对于实现我的 breadcrumb 组件并编写 “Home > Companies > Apple Inc.” 非常重要。

可以创建类似的结构吗?

angular angular2-routing
2个回答
11
投票

添加@Karsten的答案,基本上你想要的是有一个无组件路由和空路径作为默认组件,如下所示:

const privateRoutes: Routes = [
    path: 'companies',
    data: {
        breadcrumb: 'Companies'
    }
    children: [{
            path: '', //url: .../companies
            component: CompaniesComponent,
        } {
            path: 'add', //url: .../companies/add
            component: FormCompanyComponent,
            data: {
                breadcrumb: 'Add Company' //This will be "Companies > Add Company"
            }
        }, {
            path: ':id', //url: .../companies/5
            component: CompanyComponent
            data: {
                breadcrumb: 'Company Details' //This will be "Companies > Company Details"
            }
        }
    ]
];

您需要动态修改面包屑,以将“公司详细信息”更改为实际公司名称。


5
投票

如果您将

/companies/add
设为无组件路由,则
/companies/20
companies
路由仍将在第一个路由器出口内呈现。
这意味着您必须省略该路由的组件定义,它看起来像这样:

        //...
        {
            path: 'companies',
            children: [
                {
                    path: 'add',
                    component: FormCompanyComponent
                },
                {
                    path: ':id',
                    component: CompanyComponent
                }
            ]
        }

更新

        {
            path: 'companies',
            component: CompaniesComponent
        },
        {
             path: 'companies/add',
             component: FormCompanyComponent
        },
        {
            path: 'companies/:id',
            component: CompanyComponent
        }

但我认为这有点令人讨厌

© www.soinside.com 2019 - 2024. All rights reserved.