Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  165] [ 5]  / answers: 1 / hits: 16288  / 8 Years ago, tue, january 3, 2017, 12:00:00

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


More From » angular

 Answers
14

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

[#59477] Saturday, December 31, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micheleb

Total Points: 275
Total Questions: 103
Total Answers: 103

Location: Macau
Member since Sat, Jul 11, 2020
4 Years ago
;