In my Angualar 2 (final) application I need often to create a full (absolute) Url by a route name (like '/products'), e.g. to provide a permalink to a specific page or to open a page from a component in another tab/window.
Is any Angular 2 API, which allow to get an absolute Url by a route name? If no, is some known woraround for, e.g. using javascript?
I've tried location or PathLocationStrategy (e.g. prepareExternalUrl), but the method returns '/products' instead of e.g. http://localhost/products
In my Angualar 2 (final) application I need often to create a full (absolute) Url by a route name (like '/products'), e.g. to provide a permalink to a specific page or to open a page from a component in another tab/window.
Is any Angular 2 API, which allow to get an absolute Url by a route name? If no, is some known woraround for, e.g. using javascript?
I've tried location or PathLocationStrategy (e.g. prepareExternalUrl), but the method returns '/products' instead of e.g. http://localhost/products
Share Improve this question asked Jan 3, 2017 at 15:52 Alexander ZwitbaumAlexander Zwitbaum 4,8464 gold badges51 silver badges55 bronze badges 2 |3 Answers
Reset to default 5You can use PlatformLocation
to get the base_url, then you can concatenate with the return of 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
The only solution I've found for 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');
}
import { Router } from '@angular/router';
[...]
constructor(private router: Router) {
let absoluteUrl = window.location.origin + this.router.createUrlTree(['/products']);
}
window.location.host
concatenated with the return ofprepareExternalUrl
? Why do you need it?routerLink
isn't enough? – Bruno João Commented Jan 3, 2017 at 17:07