问题描述:在Angular中,当使用routerLink
属性定义锚标签的URL时,URL在href
属性中会被多次编码,导致链接无法正确跳转。
解决方法:
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); // 编码参数
}
[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 将会被正确生成并在浏览器中跳转。