Search code examples
angularangular-router

Angular - How to get current url in app component


I am trying to get current url of application in AppComponent but it always returns the root path /. Example, if I visit /users in new tab, the expected result should be /users, but when I check in the console, it shows /.

However, it works when I do the same in a child component. Below are my code:

import {Component} from '@angular/core'
import {ActivatedRoute, Router} from '@angular/router'

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['app.component.scss'],
})

export class AppComponent {
    constructor(router: Router) {    
        console.log(this.router.url) // return '/'    
    }
}

How is that possible?


Solution

  • you can subscribe to router.events and filter for NavigationEnd event to get the current active route url.

    this.router.events.subscribe((e) => {
      if (e instanceof NavigationEnd) {
        console.log(e.url);
      }
    });
    

    mention this will fail if that's no valid router defined.