如何在 TypeScript 中使用 router.navigate 打开新标签页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41531244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:32:13  来源:igfitidea点击:

How to open a new tab with router.navigate in TypeScript

typescriptknockout.jssingle-page-applicationdurandal

提问by Danielle

The following typescript code will always open in the current browser tab

以下打字稿代码将始终在当前浏览器选项卡中打开

navigate($data: menuItem, $event: JQueryEventObject) {
       //...
       let a = $event.currentTarget as HTMLAnchorElement;
       router.navigate(a.href);    
    }

How do I make router.navigate open in a newtab ? (that is when $event.ctrlKey is true)

如何让 router.navigate 在标签页中打开?(即 $event.ctrlKey 为真时)

采纳答案by Thaadikkaaran

Yes, as you @Daneille commented, you have to handle by your own way since durandal's router plugin (navigatefunction) does not provide a way to open a new tab.

是的,正如您@Daneille 评论的那样,您必须以自己的方式处理,因为 durandal 的路由器插件(导航功能)不提供打开新标签的方法。

So it is better to handle something as you commented.

所以最好按照你评论的方式处理一些事情。

if ($event.ctrlKey) { 
    window.open(url); 
}

回答by harmonickey

this is my solution

这是我的解决方案

const url = this.router.serializeUrl(this.router.createUrlTree(['/my/url/route'], { queryParams: { ...anyQueryParamsYouWantOrOmitThis } }));
window.open(url, '_blank');

回答by MNF

I think it is better to do in HTML link like this

我认为最好在这样的 HTML 链接中进行

<a  style=" text-decoration: none;" [routerLink]="['your-path',param1,param2]" target="_blank"  >your label </a>

回答by Kamil Kie?czewski

This one works with # hash (like https://example.com/#/users) and non-hash urls

这个适用于 # 哈希(如https://example.com/#/users)和非哈希网址

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

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