首页 > 解决方案 > 如何在角度路由模块中按条件重定向通配符路由

问题描述

当用户使用通配符键入错误的 URL 但通过条件控制时,是否有办法处理重定向路由?

我的项目分别有3个主要模块,每个模块都有一些只能由用户角色访问的条件。

问题是我不知道如何按条件处理它,我试过 canActivate 但它不起作用

main.ts:14 错误:路由“**”的配置无效。必须提供以下之一:component、redirectTo、children 或 loadChildren

这是我的一些代码。

const routes: Routes = [
{
    path: '',
    pathMatch: 'full',
    redirectTo: 'customer1'
},
{
    path: 'customer1',
    component: RootOneComponent,
    children: [
        {
            path: '',
            pathMatch: 'full',
            redirectTo: 'home'
        },
        {
            path: 'home',
            component: HomeOneComponent
        },
        {
            path: '**',
            component: PageNotFoundComponent
        }
    ],
},
{
    path: 'customer2',
    component: RootTwoComponent,
    children: [
        {
            path: '',
            pathMatch: 'full',
            redirectTo: 'home'
        },
        {
            path: 'home',
            component: HomeTwoComponent
        },
        {
            path: 'BlogPicture',
            loadChildren: () => import('./blog/blog.module').then(m => m.BlogModule)
        },
        {
            path: '**',
            component: PageNotFoundComponent
        }
    ],
},
{
    path: 'customer3',
    component: RootThreeComponent,
    children: [
        {
            path: '',
            pathMatch: 'full',
            redirectTo: 'home'
        },
        {
            path: 'home',
            component: HomeThreeComponent
        },
        {
            path: 'blog-price',
            loadChildren: () => import('./blog/blog.module').then(m => m.BlogModule)
        },
        {
            path: '**',
            component: PageNotFoundComponent
        }
    ],
},
 // wild card condition is there the way to manage this?
{
    path: '**',
    redirectTo: 'classic'
}

];

标签: angulartypescriptangular8angular-routing

解决方案


在你的 app.routing.module.ts

const routes: Routes = [{
    path: "customer1",
    component: FirstCustomerModule,
    pathMatch: "full"
  },
  {
    path: "customer2",
    data: { preload: true },
    loadChildren: () => SecondCustomerModule
  },
  {
    path: "customer3",
    data: { preload: true },
    loadChildren: () => ThirdCustomerModule
  }
}

path 定义了您提到的路径,并且在模块中您必须提到提到的模块将被命中。那么在你的 Modules 中你必须相对提及路径,我刚才提到了应用级路由,那么你可以进一步实现模块级路由,Load Children 告诉我们的应用它是一个模块并且它有更多的组件


推荐阅读