Angular 9如何在激活的路由参数字段内处理&符

问题描述

我正在通过if message.content == "Test": member = message.author role = discord.utils.get(member.guild.roles,id="Character Created") await bot.add_roles(member,role) ActivatedRoute方法从url中获取查询参数。对于正常的字符串来说,它可以正常工作。但是如果我在查询值中包含“&”,则将其从“ &'并在'&'位置之前获取字符串。示​​例如下:

queryParams ,这是我从中获取http://localhost:4200/#/test/APP?cat1=APP1&cat2=A&B%20Test=&cat3=Servicecat1cat2值的URL。

cat3

constructor(private actRoute: ActivatedRoute){ } this.actRoute.queryParams.subscribe(params => { this.catName1 = params['cat1']; this.catName2 = params['cat2']; this.catName3 = params['cat3']; console.log(this.catName1,this.catName2); }) 打印this.catName1,但APP1仅打印this.catName2,其余部分省略。如何将整个A值作为{ {1}}。我已经尝试过使用this.catName2函数,但是什么也没发生。

解决方法

Angular正在正常工作。 &用于分隔URL中的查询参数。因此,&在URL中具有特殊含义。 (参考:https://en.wikipedia.org/wiki/Query_string)如果您的值中包含&,则在使用前应对其进行URL编码。

要对字符串进行URL编码,可以在浏览器控制台encodeURI("<<URL>>")中进行。 您网址的编码版本为

http://localhost:4200/#/test/APP?cat1=APP1&cat2=A&B%20Test=&cat3=Service

encodeURI不编码,,/ ? : @ & = + $ #。由于您的查询参数之一具有&,请改用encodeURIComponent。注意 encodeURIComponent应该用于各个查询参数,而不要用于URL本身。

const params = {
  cat1: "APP1",cat2: "A&B Test",cat3: "Service"
};

for (const [key,value] of Object.entries(params)) {
  params[key] = encodeURIComponent(value);
}

console.log(params); // prints Object { cat1: "APP1",cat2: "A%26B%20Test",cat3: "Service" }

this.router.navigate(['/test/APP'],{ queryParams: params });

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...