如何在Angular 2中获取路由名称的绝对URL?

Ale*_*aum 11 javascript angular2-routing angular

在我的Angualar 2(最终)应用程序中,我经常需要通过路由名称(例如'/ products')创建完整(绝对)URL,例如,为特定页面提供永久链接或从另一个组件中打开页面标签/窗口.

是否有任何Angular 2 API,它允许通过路由名称获取绝对Url?如果不是,是一些已知的woraround,例如使用javascript?

我已尝试过location或PathLocationStrategy(例如prepareExternalUrl),但该方法返回'/ products'而不是例如http:// localhost/products

Bru*_*oão 5

您可以使用PlatformLocation来获取base_url,然后您可以将其与返回的连接起来prepareExternalUrl

    import { PlatformLocation } from '@angular/common';

    export class MyComponent {
        constructor(
            private platformLocation: PlatformLocation
        ){
            this.logAppStart(platformLocation);
        }

        private logAppStart(platformLocation: any){ // CHANGED THE TYPE TO ANY TO BE ABLE TO ACCESS THE LOCATION PROPERTY
            console.log(platformLocation.location); // HERE YOU FIND WHAT YOU NEED
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里找到


Ale*_*aum 4

目前我找到的唯一解决方案

import { Router } from '@angular/router';
[...]

constructor(private _router: Router) { }

  redirectNewWindow() {    
  const internalUrl = '/products';

  // Resolve the base url as the full absolute url subtract the relative url.
  var currentAbsoluteUrl = window.location.href;
  var currentRelativeUrl = this._router.url;
  var index = currentAbsoluteUrl.indexOf(currentRelativeUrl);
  var baseUrl = currentAbsoluteUrl.substring(0, index);

  // Concatenate the urls to construct the desired absolute url.
  window.open(baseUrl + internalUrl, '_blank');
}
Run Code Online (Sandbox Code Playgroud)