角度路由器 - 如何在没有正斜杠的情况下创建动态路由

问题描述 投票:3回答:1

这是我的路线阵列。我想要使​​用第一个组件的任何路由,以及使用第二个组件的任何其他路由。

[
    { 
        path: 'the-:param',
        component: MyComponent
    },
    { 
        path: ':param',
        component: MyOtherComponent
    }
]

任何想法如何实现这一目标。使用角7。

javascript angular
1个回答
4
投票

当path和pathMatch的组合不够表达时,可以提供自定义URL匹配器。

function leadingtThe(url: UrlSegment[]) {
  return url.length === 1 && url[0].path.startsWith('the-') ? ({consumed: url}) : null;
}

const routes: Routes = [{ matcher: leadingtThe, component: MyComponent }];

这应该匹配传入路径中的任何领先的the-

这里的url.length === 1确保url只有一个段,如果它不止一个那么函数返回null并且不匹配。

如果你想匹配任何以the-开头的网址,即使它有多个网段,例如localhost:4200/the-anything/segment/someothersegment,那么它应该是:

function leadingtThe(url: UrlSegment[]) {
  return url[0].path.startsWith('the-') ? ({consumed: url}) : null;
}

const routes: Routes = [{ matcher: leadingtThe, component: MyComponent }];
© www.soinside.com 2019 - 2024. All rights reserved.