Angular 4中如何获取ActivatedRoute参数中原生URL编码字符串?
解决URL编码字符串获取原始值的问题
嘿,这个问题我太熟了!浏览器会自动帮你解码URL里的百分号编码内容,所以你通过路由参数或者snapshot拿到的自然是解码后的ABCD+rAD4Og==。想要拿到原始的编码字符串ABCD%2BrAD4Og%3D%3D,可以试试这几个办法:
直接从完整URL中截取原始片段
浏览器的window.location.href会返回地址栏里的完整原始URL,你可以从中提取目标部分。比如在Angular里可以这么写:const fullOriginalUrl = window.location.href; // 假设你的路由路径是 /home/:encodedParam const encodedSegment = fullOriginalUrl.split('/home/')[1]; // 如果URL后面还有其他参数,记得再拆分掉,比如用split('?')[0] console.log(encodedSegment); // 这里就能得到 ABCD%2BrAD4Og%3D%3D对编码字符串进行二次编码后再传递
如果你能控制参数的传递过程,可以先对已经编码的字符串再做一次encodeURIComponent编码。这样浏览器自动解码一次后,得到的就是你最初的编码字符串:const firstEncoded = "ABCD%2BrAD4Og%3D%3D"; const doubleEncoded = encodeURIComponent(firstEncoded); // 此时跳转的URL会变成 localhost:4200/home/ABCD%252BrAD4Og%253D%253D // 通过snapshot获取到的参数就是 ABCD%2BrAD4Og%3D%3D,正好是你要的原始编码值利用Angular的Location服务获取原始路径
Angular的Location服务能拿到未解码的路径字符串,你可以基于此拆分出目标参数:import { Location } from '@angular/common'; import { Component } from '@angular/core'; @Component({ /* 组件配置 */ }) export class HomeComponent { constructor(private location: Location) {} getOriginalEncodedParam() { const rawPath = this.location.path(); const encodedParam = rawPath.split('/home/')[1]?.split('?')[0]; return encodedParam; } }
原理其实很简单:浏览器在加载页面时,会自动解析URL中的百分号编码(比如把%2B转成+,%3D转成=),所以框架(比如Angular)通过路由快照拿到的是解码后的结果。如果要保留原始编码形式,要么从完整原始URL中提取,要么提前做二次编码。
内容的提问来源于stack exchange,提问作者phillip chiarato
相关产品推荐
相关产品推荐

