繁体   English   中英

createUrlTree 忽略“useHash: true” RouterModule 配置

[英]createUrlTree ignores "useHash: true" RouterModule configuration

在具有“useHash: true”路由器模块配置的 Angular 7 单页应用程序中,我需要生成要在新选项卡中打开的资源的 url。

对于应用程序窗口中的路由,以下代码按预期工作:

this.router.navigate(['foo', 1]);

这意味着,它生成的 url 如下: http://localhost:4200/#/foo/1

虽然使用以下方法时: const url = this.router.createUrlTree(['foo', 1]).toString();

url 是“/foo/1”——没有“#”,所以...

window.open(url, '_blank'); 结果与无效的网址:

http://localhost:4200/foo/1

我发现的唯一解决方案(黑客)非常残酷:

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');
}

显然@angular/commonLocation类可以帮助你解决这个问题:

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设置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM