首页 > 解决方案 > 阻止用户导航到功能模块内的父路由

问题描述

我有一个带有 2 个功能模块的 Angular 10 应用程序。一个用于登陆页面,可以通过 de ' 'route 访问,延迟加载功能模块LandingPageModule。第二个是仪表板,可以通过'/dashboard'路由到达,延迟加载功能模块DashboardModule

在里面DashboardModule,我需要一个侧边栏在用户的整个导航过程中保持可见。我已经使用子路由来实现这一点,因此可以在父组件内添加侧边栏,并使用 处理子路由<router-outlet>,允许用户在子路由中导航。

中有 3 条子路线DashboardRoutingModule

我制作了路线工作流程的这个模式来完成我的解释。

在这里您可以找到实现此目的的代码

应用路由模块

const routes: Routes = [
  { path: '', loadChildren: () => import('./landing-page/landing-page.module').then(m => m.LandingPageModule) },
  { path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) },
  { path: '**', redirectTo: '' }
];

app.component.html

<router-outlet></router-outlet>

登陆页面路由模块

const routes: Routes = [{ path: '', component: LandingPageComponent }];

仪表板路由模块

const routes: Routes = [
  { 
    path: '', component: DashboardComponent, 
    children: 
    [
      { path: 'summary', component: SummaryComponent },
      { path: 'bookings', component: BookingListComponent },
      { path: 'clients', component: ClientListComponent },
    ]
  },
  { path: '**', redirectTo: '', pathMatch: 'full' }
];

仪表板.component.html

<div id="wrapper">
    <app-sidebar></app-sidebar>
    <div id="content">
        <router-outlet></router-outlet>
    </div>    
</div>

我的问题是

当用户导航到 时/dashboard,他会看到侧边栏和旁边的空白页面,因为 . 下方没有添加任何组件<router-outlet>

我的问题是

我应该怎么做才能防止用户手动导航到/dashboard

如果我使用redirectToDashboardComponent则未加载并且子路由根本不起作用。

另一个好的解决方案是删除/dashboard/summary子路由。当用户导航到/dashboard时,它将加载SummaryComponent路由器的插座并保持侧边栏可见。但我找不到任何方法让它像那样工作。

标签: angularangular2-routingangular-routingangular-module

解决方案


我只需要添加另一个处理' '.

仪表板路由模块

const routes: Routes = [
  { 
    path: '', component: DashboardComponent, 
    children: 
    [
      { path: 'summary', component: SummaryComponent },
      { path: 'bookings', component: BookingListComponent },
      { path: 'clients', component: ClientListComponent },
      { path: '', pathMatch: 'full', redirectTo: 'summary'} //New child route handling ''
    ] 
  },
  { path: '**', redirectTo: '', pathMatch: 'full' }
];

推荐阅读