Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - 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?

like image 452
Thanh Nguyen Avatar asked Jun 19 '17 03:06

Thanh Nguyen


2 Answers

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.

like image 155
Pengyy Avatar answered Sep 21 '22 12:09

Pengyy


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/

like image 30
ObjectiveTC Avatar answered Sep 20 '22 12:09

ObjectiveTC