createUrlTree忽略“ useHash:true” RouterModule配置

时间:2019-06-27 14:59:46

标签: angular angular7 angular-router

在具有“ 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');网址无效的结果:

http://localhost:4200/foo/1

我发现的唯一解决方案(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');
}

1 个答案:

答案 0 :(得分:0)

显然,@angular/common中的Location类可以帮助您解决此问题:

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