Angular - How to get current url in app component

Solution 1:

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.

Solution 2:

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/