当您在Angular中使用空路径懒加载模块时如何重定向到仪表板?

问题描述

我在Angular 9中遇到了路由问题。这是应用程序路由模块:

const routes: Routes = [
   { path: '',loadChildren: () => HomeModule,canActivate: [AuthGuard] },{ path: 'login',component: LoginComponent },{ path: 'register',component: RegisterComponent,canDeactivate: [CanDeactivateGuard] },{ path: 'payment',component: PaymentComponent },];

@NgModule({
   imports: [
       RouterModule.forRoot(routes,{ enableTracing: true })
   ],exports: [RouterModule]
})

export class AppRoutingModule {}

这里是从HomeModule懒加载的本地路由:

const routes: Routes = [
  {
    path: '',component: HomeComponent,children: [
      { path: 'dashboard',component: DashboardComponent,canActivate: [CloseDrawerGuard] },{ path: 'zones',component: ZonesComponent,{ path: 'workplaces',component: WorkplacesComponent,{ path: 'user_management',loadChildren: () => UserManagementModule },{ path: 'tenant_management',loadChildren: () => TenantManagementModule },{ path: 'schedules',component: SchedulesComponent,{ path: '',redirectTo: 'dashboard',pathMatch: 'full' },]
  }
];


@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],exports: [RouterModule]
})

export class HomeRoutingModule {}

从UserManagementModule懒惰地加载的用户管理路由。

const routes: Routes = [
    { path: '',component: UserManagementComponent,children: [
        { path: '',redirectTo: 'list',{ path: 'list',component: UserListManagementComponent,{ path: 'grid',component: UserGridManagementComponent,canActivate: [CloseDrawerGuard] }
    ]}
];

@NgModule({
    imports: [
        RouterModule.forChild(routes)
    ],exports: [RouterModule]
})

export class UserManagementRoutingModule {}

最后是TenantManagementModule的路由(同样是延迟加载)。

const routes: Routes = [
    { path: '',component: TenantUpdateComponent,{ path: 'invoices',component: InvoicesComponent,{ path: 'subscription',component: SubscriptionComponent,];

@NgModule({
    imports: [
        RouterModule.forChild(routes)
    ],exports: [RouterModule]
})
export class TenantManagementRoutingModule {}

问题是,当用户输入基本URL(spa /)时,它应该重定向到spa / dashboard,而不是重定向到spa /并显示TenantUpdateComponent,因为它具有空路径。但是,如果您在路由“ spa / tenant_management”中,则应该只评估空路径,而在基本路由“ / spa”中则不应该对空路径进行评估。它应该重定向到仪表板,这就是为什么我在家庭路由中定义此路由的原因:

{ path: '',pathMatch: 'full' }

此外,您可以访问路线“ spa / list”,但该路线不应该存在。如果您输入“ spa / user_management / list”,它应该可以工作,否则,我想将用户重定向到仪表板。

谢谢。

解决方法

您将必须在AppRoutingModule上添加一条“全部捕获”路线。

{
    // Default all the unmapped URLs to the dashboard as default
    path: '**',redirectTo: '/dashboard',pathMatch: 'full',}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...