Angular - 使用routerlink属性的锚标签的URL在href属性中被多次编码
创始人
2024-10-14 22:30:38
0

问题描述:在Angular中,当使用routerLink属性定义锚标签的URL时,URL在href属性中会被多次编码,导致链接无法正确跳转。

解决方法:

  1. 在锚标签中使用routerLink属性时,不要在URL中使用特殊字符,比如&=等。如果需要包含特殊字符,可以使用encodeURIComponent()方法进行编码。

代码示例:


Go to Page
// 在组件中编码 URL 参数
import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
  param = 'param1¶m2'; // 包含特殊字符的参数
  encodedParam = encodeURIComponent(this.param); // 编码参数
}
  1. 如果需要在URL中包含特殊字符,并且希望使用原始的URL,可以使用[routerLink]属性绑定一个方法,在该方法中手动构建URL。

代码示例:


Go to Page
// 在组件中构建 URL
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
  param = 'param1¶m2'; // 包含特殊字符的参数

  constructor(private router: Router) {}

  buildUrl(param: string): string {
    // 使用 Router 类中的 createUrlTree 方法构建 URL
    const urlTree = this.router.createUrlTree(['/page', param]);
    // 使用 Router 类中的 serializeUrl 方法将 URL 树转换为字符串
    return this.router.serializeUrl(urlTree);
  }
}

这样,URL 将会被正确生成并在浏览器中跳转。

相关内容

热门资讯

透视能赢!hhpoker有后台... 透视能赢!hhpoker有后台操作吗(透视)一直有挂(详细辅助第三方教程)1、在ai机器人技巧中,中...
攻略讲解!wepoker辅助器... 攻略讲解!wepoker辅助器安装包定制,hhpoker到底可以作弊吗,必备教程(有挂透视)1、不需...
透视好友!德州来玩辅助器(透视... 透视好友!德州来玩辅助器(透视)原来真的有挂(详细辅助安装教程)1、实时开挂更新:用户可以随时随地访...
实测交流!wepokerplu... 实测交流!wepokerplus辅助,hhpoker有透视功能吗,德州教程(有挂方法);支持2-10...
透视好友房!hhpoker辅助... 透视好友房!hhpoker辅助挂是真的吗(透视)一直是有挂(详细辅助黑科技教程);1、不需要AI权限...
最新研发!hhpoker必备开... 最新研发!hhpoker必备开挂,wepoker有透视吗,揭秘攻略(有挂教程);原来确实真的有挂(需...
透视辅助!wepokerplu... 透视辅助!wepokerplus作弊(透视)原来真的有挂(详细辅助细节方法)1、构建自己的辅助插件;...
玩家必用!佛手大菠萝有挂吗,德... 玩家必用!佛手大菠萝有挂吗,德普之星有辅助软件吗,AI教程(有挂教程)这是由厦门游乐互动科技有限公司...
透视了解!hhpoker可以控... 透视了解!hhpoker可以控制吗(透视)本来真的是有挂(详细辅助普及教程);小薇(透视辅助)致您一...
交流学习经验!sohoo开挂辅... 交流学习经验!sohoo开挂辅助,wepoker脚本,详细教程(有挂方法)1、不需要AI权限,帮助你...