角路由多条路径到同一组件

角路由多条路径到同一组件

本文介绍了角路由多条路径到同一组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以对此进行优化

Is there a way to optimize this code from this

{
  path: 'access-requests',
  canActivate: [AccessGuard],
  component: AccessRequestsComponent,
  children: [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      path: 'today',
      component: AccessRequestsComponent
    },
    {
      path: 'tomorrow',
      component: AccessRequestsComponent
    },
    {
      path: 'expired',
      component: AccessRequestsComponent
    }
    ]
}

像这样

{
  path: 'access-requests',
  canActivate: [AccessGuard],
  component: AccessRequestsComponent,
  children: [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      path: 'today | tomorrow | expired',
      component: AccessRequestsComponent
    }
    ]
}

推荐答案

您可以使用 UrlMatcher 属性.

{
  path: 'access-requests',
  canActivate: [AccessGuard],
  component: AccessRequestsComponent,
  children: [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      matcher: matcherFunction,
      component: AccessRequestsComponent
    }
    ]
}

还有

export function matcherFunction(url: UrlSegment[]) {
    if (url.length == 1) {
        const path = url[0].path;
         if(path.startsWith('today')
           || path.startsWith('tomorrow')
           || path.startsWith('expired')){
          return {consumed: url};
        }
    }
    return null;
}

注意:未经测试的代码

这篇关于角路由多条路径到同一组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-02 08:17