angular - createUrlTree 忽略“useHash: true”RouterModule 配置
问题描述
在具有“useHash:true”路由器模块配置的Angular 7单页应用程序中,我需要生成要在新选项卡中打开的资源的url。
对于应用程序窗口中的路由,以下代码按预期工作:
this.router.navigate(['foo', 1]);
这意味着,它会生成如下网址: http://localhost:4200/#/foo/1
虽然使用以下方法时: const url = this.router.createUrlTree(['foo', 1]).toString();
url 是“/foo/1” - 没有“#”,所以...
window.open(url, '_blank'); 结果无效的 url:
我发现的唯一解决方案(hack)非常残酷:
window.open('#' + url, '_blank');
RouterModule.forRoot(routes, {
useHash: true,
onSameUrlNavigation: 'reload',
}
showItem(item: Item) {
// THIS WORKS AS EXPECTED
this.router.navigate(['item', item.id]);
}
showItemInNewTab(item: Item) {
const url = this.router.createUrlTree(['item', item.id]).toString();
// THIS WORKS BUT ITS A HACK :/
window.open('#' + url, '_blank');
}
解决方案
显然这个Location
类@angular/common
可以帮助你解决这个问题:
import { Location } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(
private _urlSerializer: UrlSerializer,
private _location: Location,
public router: Router) {
}
ngOnInit() {
let tree = this.router.createUrlTree(['/profile']);
// The call to Location.prepareExternalUrl is the key thing here.
console.log(this._location.prepareExternalUrl(this._urlSerializer.serialize(tree)));
// As far as I can tell you don't really need the UrlSerializer.
}
}
当我对此进行测试时,它尊重路由器的useHash
设置。
推荐阅读
- r - quanteda 中的 tokens_compound() 改变了特征的顺序
- node.js - node.JS / sequelize 关联数据库表
- amazon-web-services - 创建 IAM 角色时出错 - 属性 PolicyDocument 的值必须是对象
- telegram - 如何在电报中深度链接直接消息
- curl - 从另一个 URL 上传文件而不在本地保存时保留 Content-Type
- java - 在 Linux 服务器上的 Jar 中运行 Cucumber 功能
- c# - 有什么东西可以让这个立方体在 Unity 中爬升吗
- selenium - 是否有可能,如果可以,如何使用 RobotFramework 清除 localStorage?
- c - 在 Linux 和其他操作系统上,真正的软件内部是否有内核模块
- c++ - 更新 OPENGL 中的顶点和索引