Angular5带字符串约束路由定义及含.vpf的URL路由配置问题
Angular 5路由约束与匹配问题解决方案
我来帮你搞定这两个路由相关的问题,都是日常开发里很常见的需求,话不多说直接上方案:
问题1:在Angular 5的app.routes.ts中定义带字符串约束的路由
Angular路由支持通过正则表达式来约束路由参数的格式,你只需要在参数名称后面加上括号,里面写入对应的正则规则即可。
举几个实用的例子:
- 约束参数只能是指定的几个字符串(比如只能是
products或categories):const routes: Routes = [ { path: ':section(products|categories)', component: SectionBasedListingComponent } ]; - 约束参数必须以特定后缀结尾(比如
.vpf):
注意:TypeScript字符串里的反斜杠需要转义,所以正则里的const routes: Routes = [ { path: ':section(.*\\.vpf)', component: SectionBasedListingComponent } ];\.要写成\\.。
问题2:让包含.vpf的URL也导航到SectionBasedListingComponent
你的现有路由{path:':section',component:SectionBasedListingComponent}其实默认就能匹配所有类似/anystring的路径,包括/something.vpf。如果实际场景中它没生效(比如有优先级更高的路由拦截了),或者你想明确指定规则,推荐两种方案:
方案一:修改现有路由的参数约束,明确匹配含.vpf的路径
如果你希望:section参数可以包含.vpf(不管位置),或者必须以.vpf结尾,可以修改路由的正则规则:
const routes: Routes = [ // 先匹配带.vpf的路径(更具体的规则放前面) { path: ':section(.*\\.vpf.*)', component: SectionBasedListingComponent }, // 再匹配任意字符串的路径 { path: ':section', component: SectionBasedListingComponent } ];
如果只需要匹配以.vpf结尾的路径,把正则改成(.*\\.vpf)即可。
方案二:添加独立路由条目匹配带.vpf的路径
如果你想把带.vpf的路径作为单独的规则,可以新增一个路由放在原有路由前面(Angular路由按从上到下顺序匹配,先匹配到的生效):
const routes: Routes = [ // 匹配类似/sample.vpf的路径,sample会作为section参数的值 { path: ':section.vpf', component: SectionBasedListingComponent }, // 原来的任意字符串路由 { path: ':section', component: SectionBasedListingComponent } ];
这种方式下,你在组件里通过ActivatedRoute获取section参数时,拿到的是.vpf前面的部分(比如/sample.vpf对应的参数值是sample)。
内容的提问来源于stack exchange,提问作者kamalav
相关产品推荐
相关产品推荐

