Dheeraj Kumar
Dheeraj Kumar

Reputation: 4175

How to get current URL in Angular 2.0+

I know this has been asked many times and I have tried to look for a solution.

My current URL is: http://localhost:4200/configuration

Below is one of the many online found solutions I am trying to implement.

export class AppComponent implements OnInit{
  title = 'app';
  constructor(private router: Router, private activatedRoute: ActivatedRoute) { 

  }

  ngOnInit() { 
    console.log("On Init");
    console.log(this.router.url);
    console.log(this.activatedRoute.url);
    //this.router.navigate(['/login']);
  }
}

On reload of page I get below output.

On Init 
\

I am just getting empty url. I am very curious to know what I am missing.

Upvotes: 5

Views: 11934

Answers (3)

Vega
Vega

Reputation: 28738

This will give "/configuration"

import { Router, NavigationEnd } from '@angular/router';
import { isPlatformBrowser } from '@angular/common';

....

constructor(
    private router: Router,
....

ngOnInit() {
    if (isPlatformBrowser) {
      this.router.events
        .filter(event => event instanceof NavigationEnd)
        .subscribe(() => {
          console.log(this.router.routerState.snapshot.url);
        })
    }
  }

or

  ngOnInit(){
    console.log(this.router.url)
  }

Upvotes: 2

csga5000
csga5000

Reputation: 4151

You are accessing the property correctly. However, you're accessing it before it's set. See:

https://stackblitz.com/edit/angular-8phmvc

If you check the browser log you can see which part of each component's lifecycle has it set.

But long story short, instead of ngOnInit try ngAfterViewChecked or look for another way to subscribe to the current location using router.

Upvotes: 0

FAISAL
FAISAL

Reputation: 34701

You can do it using location.href. Another option is to use DOCUMENT from '@angular/platform-browser':

import { DOCUMENT } from '@angular/platform-browser';

constructor(@Inject(DOCUMENT) private document: any){
    console.log(location.pathname);
    console.log(location.href);
    console.log(this.document.location.href);
}

If you only want to get "/configuration" from your url, then use location.pathname.

Demo here.

Upvotes: 11

Related Questions