Extract the ID from the Router's URL

I am currently working on a project where I need to keep a log of every page that is accessed in my Angular application.

Here is an overview of my routing setup:

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

Within my app component's TypeScript file, in the ngOnInit() method, I have added the following code:

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

For example, when trying to access the URL /testing123,

I am expecting the log to show "/testing123", However, it is currently only logging "/" without passing the ID.

Answer №1

If you need to retrieve the id from the router URL, the following code can be very handy:

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']);
      }
    );
  }

}

Answer №2

Below is the code snippet to capture logs of each successful route:

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

export class Tracker {

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shifting focus among an array of standard <input> controls with each keystroke

When working with Angular, I encountered a situation where I have an array of arrays of numbers, as shown below: [ [1,1,1,1], [1,1,1,1] ] In my HTML file, I am using ngFor to generate input controls like this: <table> <tbody> ...

Cypress: Importing line in commands.ts is triggering errors

After adding imports to the commands.ts file, running tests results in errors. However, in commands.ts: import 'cypress-localstorage-commands'; /* eslint-disable */ declare namespace Cypress { interface Chainable<Subject = any> { c ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

Issue with ngModel being undefined after data has finished loading in Ionic 3

As a newcomer to Angular 4, I've been struggling to find a solution for a seemingly simple issue related to an Ionic app. Whenever a user logs in, the entire user object is saved to localStorage. Despite trying various plugins, I settled on a straight ...

Extracting Date and Time Information from matDatepicker in Angular 6 Material

Below is the code snippet present in my html file: <mat-form-field> <input matInput [matDatepicker]="myDatepicker" placeholder="Choose a date" [(ngModel)]="model.value" name="value"> <mat-datepicker-toggle matSuffix [for]="myDatepic ...

Set the value of HTML input type radio to a nested JSON string

Currently, I'm developing an Angular application and encountering an issue where I am unable to access the nested array value 'subOption.name' for the input type radio's value. I'm uncertain if the error lies within the metaData st ...

Angular Karma encountered an error: TypeError - It is unable to read the property '_id' as it is undefined

Encountering an issue while testing with karma jasmine, the error message appears as... TypeError: Cannot read property '_id' of undefined This is the Component.ts file: import { Component, OnInit } from '@angular/core'; import { ApiSe ...

The condition will be false if a number is present, even if it is zero

I am facing an issue with a class containing an optional field called startDateHour: export class Test { startDateHour?: number; // more fields, constructor etc. } I need to perform an action only if the startDateHour exists: if (test.startDateHour ...

Error TS2322: This type cannot be assigned to type 'never' in Angular

Trying to incorporate the websocket (sockjs and stomp) into my Angular project for a chat messaging feature, I encountered an issue in my service.ts file. Specifically, when I defined the addMessage method like so: public messages = []; addMessage(messa ...

What is the best way to retrieve the deviceValue in another function?

currentStatus: string = ""; updateStatus(deviceValue) { this.currentStatus = deviceValue.valueOf(); return this.currentStatus; } update(value: string, index: number, item: number) { this.updateStatus(???); alert(this.currentStatus); ...

Exploring JSON object nesting

I need to extract specific objects (fname, lname, etc.) from the data received in node.js from an Angular front-end. { body: { some: { fname: 'Fuser', lname: 'Luser', userName: 'userDEMO', pas ...

Cancelling an ongoing AWS S3 upload with Angular 2/Javascript on button click

I'm currently working with Angular 2 and I have successfully implemented an S3 upload feature using the AWS S3 SDK in JavaScript. However, I am now facing a challenge: how can I cancel the upload if a user clicks on a button? I've attempted the ...

How can I set up timers and display their outcomes?

I recently built a timer using RXJS: let timer1value = null; let timeFinish = 30; let finishDate = new Date(); return timer(1000) .pipe( takeWhile(() => new Date() < finishDate), finalize(() => { timeFinish = fini ...

The Div element triggers a focus event when either the div itself is selected or any nested input field is selected - Angular

Within an Angular application, I have a Div element with an index tab that allows for selection. This Div contains a form with various fields and buttons. My goal is to trigger the focus event on the Div whenever the Div itself is selected or any element w ...

Instructions for activating "error prevention only" in TSLint: How can you turn off style checks and other features?

After creating and running my first Vue.js + TypeScript project, I decided to reformat the TypeScript code to my liking. However, when I ran the npm run serve command, I received the following warning: WARNING in .../src/app/app.ts 7:1 misplaced opening b ...

Encountering Invalid Chai attribute: 'calledWith'

I am currently in the process of implementing unit tests for my express application. However, I encountered an error when running the test: import * as timestamp from './timestamp' import chai, { expect } from 'chai' import sinonChai f ...

Displaying individual information for each Bootstrap modal in Angular can be achieved by properly binding the data

While looping through images, a modal pops up with its information when clicked. The issue is that all the modals associated with different images display the same content as the first image. This is what has been attempted: data:any; HTML <div *ngFo ...

Fade-in and fade-out animations in Angular triggered by a click event

I developed a fade-in, fade-out animation for a div element. My goal is to achieve the following: Upon initial page load, there is a div element that displays some numbers. On the right and left sides of the div, there are two buttons. When a user cl ...

New post: "Exploring the latest features in Angular

Looking for help with integrating Angular and SpringREST to fetch data from the backend? Here's my situation: I need to retrieve a JSON string from the backend using a POST request, send it to my site's hosted link, and display it on the user int ...

An error was encountered at line 52 in the book-list component: TypeError - The 'books' properties are undefined. This project was built using Angular

After attempting several methods, I am struggling to display the books in the desired format. My objective is to showcase products within a specific category, such as: http://localhost:4200/books/category/1. Initially, it worked without specifying a catego ...