Angular路由参数添加后缀后如何获取纯参数值?
问题
我原本的路由配置是这样的:
{ path: 'store/:storeId/.', component: StoreComponent }
访问 https://localhost/store/kfc/ 时,能通过 this.route.snapshot.paramMap.get('storeId') 拿到kfc这个参数值。
现在需要把URL改成 https://localhost/store/kfc-store/,也就是给storeId加上-store后缀,但希望还是能通过storeId参数获取到纯的kfc,而不是带后缀的完整字符串。我试着把路由改成了:
{ path: 'store/:storeId-store/.', component: StoreComponent }
但这时候用this.route.snapshot.paramMap.get('storeId')一直返回null,用this.route.snapshot.paramMap.get('storeId-store')拿到的是kfc-store,不是我要的纯值。请问怎么通过路由配置直接获取纯的storeId值?
解决方案
方法1:利用路由参数的正则匹配直接提取
Angular路由支持给参数添加正则表达式来限定匹配规则,把路由配置改成下面这样就行:
{ path: 'store/:storeId(.*?)-store/.', component: StoreComponent }
这里的(.*?)是非贪婪正则匹配,会精准捕获-store前面的所有内容作为storeId参数,之后再用this.route.snapshot.paramMap.get('storeId')就能直接拿到kfc这种纯值了。
方法2:获取参数后手动截取后缀
如果觉得正则配置太繁琐,也可以退一步,先获取带后缀的完整参数,再手动去掉-store后缀:
const fullStoreId = this.route.snapshot.paramMap.get('storeId-store'); const storeId = fullStoreId ? fullStoreId.replace('-store', '') : null;
这种方式简单直接,适合不需要复杂路由匹配的场景。
内容的提问来源于stack exchange,提问作者jojo
相关产品推荐
相关产品推荐

