获取将由 router.navigate 生成的 URL

Get URL that would be generated by router.navigate

我想知道是否有办法在调用 [=12] 时获取 由 Angular 的路由器生成的 =]方法。

例如:

this._router.navigate(['browse'], { queryParams: { section: 'users', isActive: true } });

可能会导航到 /browse#?section=users&isActive=true

如何在不执行导航或不更新浏览器 URL 的情况下获取此路线?

查看 的选定答案 您可以订阅您的路由器导航事件并添加 "skipLocationChange" 参数以避免切换 URL

看看createUrlTree:

this._router.createUrlTree(
    ['browse'], { queryParams: { section: 'users', isActive: true } });

返回的对象,UrlTree 有一个 toString 函数,可以满足您的需求。

source可以看出,navigate实际上在内部使用了createUrlTree

navigate(commands: any[], extras: NavigationExtras = {skipLocationChange: false}):
        Promise<boolean> {
    validateCommands(commands);
    return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
}

这一个适用于:散列(例如 https://site/#/user)和非散列 url

public openInNewTab(router: Router, namedRoute) {
    let newRelativeUrl = router.createUrlTree([namedRoute]);
    let baseUrl = window.location.href.replace(router.url, '');

    window.open(baseUrl + newRelativeUrl, '_blank');
}