【问题标题】:How to redirect wildcard route by condition in angular routing module如何在角度路由模块中按条件重定向通配符路由
【发布时间】:2020-06-15 12:50:54
【问题描述】:

当用户使用通配符输入错误的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'
}

];

【问题讨论】:

    标签: angular typescript angular8 angular-routing


    【解决方案1】:

    在你的 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告诉我们的应用它是一个模块,它还有更多的组件

    【讨论】:

    • 条件使用 this : if(condition) { this.router.navigate(["/whatever"]); }
    • 哦,是的,我忘了在 Angular v.8 之后更新我的代码
    • 我刚刚更新了我的代码,你能再看看吗?
    • 通过在末尾替换redirectTo来使用组件
    • 如果你想使用重定向然后添加 pathMatch = "full"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 2017-08-21
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多