Angular 路由到同一组件的多条路径

标签 angular

有没有办法从这里优化这段代码

{
  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属性(property)。

    {
      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;
    }

注意:未经测试的代码

关于 Angular 路由到同一组件的多条路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46364810/

相关文章:

html - 在 mat-h​​eader-col 中垂直居中文本?

angular - 如何在页面初始化时翻译用 ngif 隐藏的文本?

javascript - 无法在 Angular 2 中从父组件更新子组件 View

angular - 为什么 Checkbox [checked] 为所有选项触发多次

angular - node_modules/@ngrx/store/src/models.d.ts(58,58) : error TS2304: Cannot find name 'unknown' 中的错误

angular - 使用 *ngFor 自定义模板渲染

angular - 如何在 ngx bootstrap datepicker 中更改消息 "Invalid Date"而不位于节点模块中

javascript - 在 Angular 服务中使用 BehaviorSubject?

angular - 从 Angular 2 应用程序的任何地方关闭辅助路由

javascript - 使用 canActivate 防护时 redirectTo 不起作用