Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

I've essentially run into this problem, where I need a reference to the current route to use gradients, but have yet to figure out how to translate the solution into Angular 2.

like image 681
Kevin Stricker Avatar asked Sep 06 '25 14:09

Kevin Stricker


2 Answers

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 ('/'), 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

like image 96
Günter Zöchbauer Avatar answered Sep 09 '25 04:09

Günter Zöchbauer


You can use the DOCUMENT injection from @angular/common.

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({...})
class SomeComponent {
  constructor(@Inject(DOCUMENT) document: any) {
    console.log(document.location.href);
  }
}
like image 41
guduf Avatar answered Sep 09 '25 05:09

guduf