How do I get the absolute path of the current page in Angular 2?

constructor(location:Location) {
  console.log(location.prepareExternalUrl(location.path()));
}

https://angular.io/api/common/Location#prepareexternalurl

As the documentation says:

Normalizes an external URL path. If the given URL doesn’t begin with
a leading slash (“https://stackoverflow.com/”), adds one before normalizing. Adds a hash if
HashLocationStrategy is in use, or the APP_BASE_HREF if the
PathLocationStrategy is in use.

It means that you have to explicitly specify APP_BASE_HREF to get an absolute path in Angular 5+.

window.location provides more information

Plunker example

Leave a Comment