在Angular中,如果需要构建URL,可以使用Angular Router来进行构建。在构建URL时,可以使用Router API中的createUrlTree()方法,该方法接受一个参数数组,该数组包含路由参数和选项。如下所示:
import { Router } from '@angular/router'
// 构建URL
const urlTree = this.router.createUrlTree(['/example', 123], {
queryParams: { 'param1': 'value1', 'param2': 'value2' },
fragment: 'anchor'
});
// 导航到URL
this.router.navigateByUrl(urlTree);
在上面的代码中,createUrlTree()方法将参数数组['/example', 123]转换为一个URL树对象,该对象可以用于导航。选项参数包含查询参数和片段。
可以自定义路由路径中的参数格式。例如,使用参数{}包含参数名称。
const urlTree = this.router.createUrlTree(['/example', {param1: 'value1', param2: 'value2'}]);
更多Router API可以参考官方文档:https://angular.io/api/router/Router#createUrlTree