角度路由到同一组件的多个路径

Rac*_*naa 8 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
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这样的事情

{
  path: 'access-requests',
  canActivate: [AccessGuard],
  component: AccessRequestsComponent,
  children: [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      path: 'today | tomorrow | expired',
      component: AccessRequestsComponent
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

Bog*_*n D 13

您可以使用映射数组:

children: [
  // excluding the other paths for brevity
  ...['today', 'tomorrow', 'expired'].map(path => ({
    path,
    component: AccessRequestsComponent
  }))
]
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此方法将导致 Angular 在不同路径之间切换时重新加载组件,这可能是也可能不是您想要的。 (8认同)
  • @DaneBrouwer 感谢您的反馈!关于“更好的实践”部分:虽然更通用,但是使用 url 匹配器的方法更慢、更复杂并且没有必要(因为在我们的例子中没有任何好处)。我认为 KISS 是一个很好的实践 (3认同)
  • 我意识到上述可能是更好的做法,但这对我来说似乎更具可读性。 (2认同)

Cor*_*elC 10

您可以使用UrlMatcher属性.

{
  path: 'access-requests',
  canActivate: [AccessGuard],
  component: AccessRequestsComponent,
  children: [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      matcher: matcherFunction,
      component: AccessRequestsComponent
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

注意:未经测试的代码

  • 是的,可以使用这样的东西。我们可以看看 [defaultUrlMatcher](https://github.com/angular/angular/blob/4.4.5/packages/router/src/shared.ts#L112) 如何进行路径匹配作为示例。 (2认同)