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?
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.
In Angular 4, you can get the full path string from within app.component.ts by using the Location module.
Eg, In your browser, when you navigate to "http://yoursite.com/products/cars?color=red&model=202", the code below will output pathString "/products/cars?color=red&model=202".
In app.component.ts
import { Component } from '@angular/core';
import { Router} from '@angular/router';
import { Location } from '@angular/common';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
    constructor(
    private location: Location
  ) { 
      var pathString = location.path();
      console.log('appComponent: pathString...');
      console.log(pathString);       
  }
}
*Credit: https://tutorialedge.net/post/typescript/angular/angular-get-current-route-location/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With