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
To link pages using relative URL in HTML, use the <a> tag with href attribute. Relative URL is used to add a link to a page on the website. For example, /contact, /about_team, etc.
path(); You need to add ROUTER_DIRECTIVES somewhere so Angular can resolve Location . You need to add import: [RouterModule] to the module. In the V3 (RC. 3) router you can inject ActivatedRoute and access more details using its snapshot property.
Href is the basic attribute provided by Html to navigate through pages which reloads the page on click. routerLink is the attribute provided by angular to navigate to different components without reloading the page.
Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.
You 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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With