I need to get the current URL present in the browser in my Angular 2 application.
In JavaScript normally we do it using the window object.
How can I do this
This is late but I thought it was worth updating. As of Angular2 final release you can import DOCUMENT from @angular/common and use that to get to the location.
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
...
export class YourComponent {
constructor(@Inject(DOCUMENT) private document: Document) {
console.log(this.document.location.href);
}
}
It is not necessary to import complicated packages or inject something. Just use the methods you can find on window.location
!
Such as:
window.location.href
gives you the full URLwindow.location.hostname
gives you the host namewindow.location.origin
with this command you get the host name with protocol (e.g. https://)For IE<=10 users: location.origin may not be available, then you have to use
location.protocol + "//" + location.hostname
or use a polyfill or package like location-origin
You can
Location
and get the URL by location.path()
(see also Location and HashLocationStrategy stopped working in beta.16)window.location.pathname
See also
How do I get the absolute path of the current page in Angular 2?
This Link helped me:
public static getCurrentAbsoluteSiteUrl(): string {
if (window
&& "location" in window
&& "protocol" in window.location
&& "pathname" in window.location
&& "host" in window.location) {
return window.location.protocol + "//" + window.location.host + window.location.pathname;
}
return null;
}
For future travelers, a lot of the other answers are great. Another option, if you want everything before the pathname (e.g. https://example.com
) then you can use:
window.location.origin
Here's a W3 article on the different window.location
properties you can use:
http://www.w3schools.com/js/js_window_location.asp
Cheers!
Import the ActivatedRoute, (and the rest of the Router stuff too, if you want)
import { ActivatedRoute, Params, Router, UrlSegment } from '@angular/router';
making sure it's injected into the constructor,
constructor(private route: ActivatedRoute) { ... }
and on ngOnInit you can use this.route
to inspect the URL. For instance, all the segments are in an array, which you can string together, as @ibgib suggested, like this:
let path = this.route.snapshot.url.join('/');
to give you something like "mars/moons/phobos".