Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 927
Dheeraj Kumar Avatar asked Dec 23 '22 14:12

Dheeraj Kumar


2 Answers

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.

like image 140
Faisal Avatar answered Dec 26 '22 17:12

Faisal


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)
  }
like image 34
Vega Avatar answered Dec 26 '22 18:12

Vega