How to get absolute URL by route name in Angular 2?

In my Angualar 2 (final) application, I often need to create a complete (absolute) Url by the name of the route (e.g. '/ products'), for example. to provide a permanent link to a specific page or open a page from a component in another tab / window.

Is there any Angular 2 API that allows you to get absolute url by the name of the route? If not, then this is a known issue for example. using javascript?

I tried location or PathLocationStrategy (e.g. prepareExternalUrl), but the method returns '/ products' instead, for example. http: // localhost / products

+4
source share
3 answers

The only solution I found now

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

You can use PlatformLocationto get base_url, then you can combine with return 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
        }
    }

Found here

+1
source
import { Router } from '@angular/router';

[...]

constructor(private router: Router) { 
  let absoluteUrl = window.location.origin + this.router.createUrlTree(['/products']);
}
0
source

Source: https://habr.com/ru/post/1665635/


All Articles