user10181542
user10181542

Reputation: 1380

Get ID from Router URL

I am trying to log every page accessed in my angular application.

My route is like so:

const routes: Routes = [
  { path: ':id', component: AppComponent}
];

My app.component .ts onInit:

ngOnInit() {
  console.log(this.router.url);
}

When I access /testing123

I want it to log "/testing123" But instead is logging "/" without the ID passed.

Upvotes: 2

Views: 2387

Answers (2)

Md. Masudur Rahman
Md. Masudur Rahman

Reputation: 1078

The following code might be useful to log the id from the router URL:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params} from '@angular/router';

export class AppComponent implements OnInit {

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe(
      (params: Params) => {
        console.log(params['id']);
      }
    );
  }

}

Upvotes: 5

Dinesh Hiregange
Dinesh Hiregange

Reputation: 113

Use below code to get log of every successful route.

import { NavigationEnd, Router } from '@angular/router';

export class ClassName {

constructor(private router: Router) {
router.events.subscribe((evt) => {
  if (evt instanceof NavigationEnd) {
   console.log(evt.url);
  }
})
}

Upvotes: 1

Related Questions