【问题标题】:Prevent user from navigating to parent route inside feature module阻止用户导航到功能模块内的父路由
【发布时间】:2020-09-09 19:59:26
【问题描述】:

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

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

DashboardRoutingModule 中有 3 个子路由:

  • '/dashboard/summary'加载中SummaryComponent
  • '/dashboard/bookings'加载中BookingListComponent
  • '/dashboard/clients'加载中ClientListComponent

我做了这个schema of the route workflow 来完成我的解释。

这里你可以找到实现这个的代码

AppRoutingModule

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>

LandingPageRoutingModule

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

DashboardRoutingModule

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

dashboard.component.html

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

我的问题是

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

我的问题是

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

如果我使用redirectToDashboardComponent 不会加载,子路由根本不起作用。

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

【问题讨论】:

    标签: angular angular2-routing angular-routing angular-module


    【解决方案1】:

    我只需要添加另一个处理' ' 的子路由。

    DashboardRoutingModule

    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' }
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 2023-04-06
      • 2019-04-19
      • 2018-01-28
      • 2019-03-04
      • 2018-06-23
      相关资源
      最近更新 更多