Exploring Angular routing with parameters and extracting parameter values

In an email, a user will click on a link that looks like this:

do-something/doSomething?thing=XXXXXXXXXXX

I'm trying to figure out how to define the route in the router and subscribe to get params. Here's what I currently have set up in the router:

    {
     path: 'do-something/:id',
     component: DoSomethingComponent
    },

And in the component:

    ngOnInit() {
     this.sub = this.route
      .params
      .subscribe(params => {
       console.log(params)
      });
    }

But for some reason, the route never matches. Shouldn't anything after "reset-password" be considered as a param by ":id"?

Answer №1

This specific code snippet is tailored for an Angular website.

import { Component, OnInit }  from '@angular/core';
import { ActivatedRoute }     from '@angular/router';
import { Observable }         from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  template:  `
    <p>Dashboard</p>
    <p>Session ID: {{ sessionId | async }}</p>
  `
})
export class AdminDashboardComponent implements OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
   //read query param
    this.route
      .queryParamMap
      .map(params => console.log(params.get('thing')););

     //read param value 
      this.route
      .paramMap
      .map((params: ParamMap) => 
                           console.log(params.get('id')));
  }
}

If you want to learn more about routing in Angular, check out the documentation here.


Here's an example of how to implement navigation:

const appRoutes: Routes = [
  { path: 'do-something/:id', component: DoSomethingComponent, name: 'Details'}];

To navigate using the above configuration:

this.router.navigate( [
  'Details', { id: 'idvalue', param1: 'value1'
}]);//this you can try from code

Ensure the URL matches like this:

do-something/idvalue?param1=value1. //try this from browser

To read query parameters, follow this approach:

ngOnInit() {
  // Capture the access token and code
  this.route
      .queryParams
      .subscribe(params => {
          let thing = params['thing'];
      });
}

Alternatively, you can use this method to retrieve query parameters:

(new URL(location)).searchParams.get("parameter_name")

Answer №2

Spent over an hour trying to figure this out.

Both of the methods below were unsuccessful:
this.route.paramMap &
this.route.params

Only the following method worked:
this.route.queryParams

Here is the URL structure:

http://localhost:4200/employee?tab=admin

Extracting the value of the query parameter tab, which is admin, was the goal.

The code snippet that finally worked is:

ngOnInit() {
   this.route.queryParams.subscribe(params => {
    console.error(" ==== ", params["tab"]); // this will print `admin`
    // this.tabNameFromUrl = params["tab"];
  });
}

Hopefully, this explanation clears things up.

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

The usage of Angular Tap is no longer recommended or supported

My Angular application contains the following HTTP interceptor: import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpResponse } from '@angular/common/http'; ...

What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in makin ...

Tips for positioning an inline label and input field in an Angular application using CSS and HTML: How to align the label to the left and the input

I'm currently developing an Angular form with multiple label-input field combinations. I have managed to style the labels and input fields with inline block so that they appear on the same row. However, I am facing a challenge in aligning the label to ...

Angular appears to be having trouble with localStorage functionality

Having an issue with my service that interacts with a local NOTES object array using localStorage. Whenever the page refreshes, the previously entered data is lost and only the initial data in the const NOTES array remains. Can't seem to figure out wh ...

Tips for testing a service in Angular using unit testing techniques

Within my service, I have a function that looks like this: exportPayGapDetails(filterObject: PayGapDetailFilter): void { const url = `${this.payGapDetailExportUrls[filterObject.type]}`; this.http .post<PollInitResponse>( `/adpi/rest/v2/s ...

Exploring ways to conduct a thorough scan of object values, inclusive of nested arrays

My goal is to extract all values from an object. This object also includes arrays, and those arrays contain objects that in turn can have arrays. function iterate(obj) { Object.keys(obj).forEach(key => { console.log(`key: ${key}, value: ${o ...

Node appears to be struggling to find the cors

I added the cors package and confirmed that it's inside the node_modules directory. However, I keep encountering this error message. /usr/src/app/node_modules/ts-node/src/index.ts:859 server | return new TSError(diagnosticText, diagnosticCodes, ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

Creating a personalized design for MUI TextField spin button

Looking to customize the appearance of the up/down spin buttons in MUI TextField. https://i.sstatic.net/DcG66.png Desiring white arrows and a black surrounding area that's slightly larger, akin to this: https://i.sstatic.net/ZxMJw.png I'm aware ...

What is the process for incorporating the jsnetworkx library into an ionic or angular 4 project?

When using any Ionic3 app service import * as jsnx from 'jsnetworkx'; The output error message is: Uncaught (in promise): Error: Cannot find module "lodash/lang/isPlainObject" Error: Cannot find module "lodash/lang/isPlainObject" at webpackMis ...

I'm struggling to transfer information from my form to TypeScript in Angular

Currently, I am working on developing a fullstack application using Node.js and Angular (material UI). However, I have encountered an issue that I need help with. I am trying to figure out how to retrieve data from an Angular form for a small web resource ...

Apply a see-through overlay onto the YouTube player and prevent the use of the right-click function

.wrapper-noaction { position: absolute; margin-top: -558px; width: 100%; height: 100%; border: 1px solid red; } .video-stat { width: 94%; margin: 0 auto; } .player-control { background: rgba(0, 0, 0, 0.8); border: 1px ...

The Selenium tests are running smoothly, however, despite their successful execution, I am not receiving any pass results as the assertions seem

Currently, I am in the process of incorporating Selenium (v4.18.1) tests into an Angular web application specifically for the Microsoft Edge browser (v122.0.2365.59). The necessary Microsoft Edge WebDriver (v122.0.2365.59) has been successfully installed. ...

Employing the filter or find technique to extract an element contained within a JSON data structure

Is it possible to retrieve one of these items using the filter or find method to search for a match within the fiberAgrupations array? I attempted the following: const landlineRate = this.monolineJsonRates[0].cambioCaudal.getAll() .filter(landlinedRat ...

How to outsmart the TypeScript compiler when integrating a library without type definitions?

Is there a way to deceive the compiler into thinking that certain definitions are being used? My constructor contains: nv.addGraph(()=> {...}) Before my class declaration, I include: public nv:nv; In my model file, I define: export interface nv{ ...

Inject SCSS variables into Typescript in Vue 2 Using Vue-cli 5

When working on my Vue 2 project (created using the Vue-cli v4), I successfully imported variables from my SCSS file into my typescript (.vue files) without any issues. I had the :export { ... } in my SCSS file _variables.scss, along with shims.scss.d.ts ...

Is it possible to use a TypeScript Angular (click) event with an object property as the value?

Seeking assistance in creating a dynamic error card featuring various error messages along with a retry button. Below is a snippet from my TypeScript object: errorCard: any = []; if(error) { this.errorCard.errorMessage = "Oops, please try again"; ...

What sets 'babel-plugin-module-resolver' apart from 'tsconfig-paths'?

After coming across a SSR demo (React+typescript+Next.js) that utilizes two plugins, I found myself wondering why exactly it needs both of them. In my opinion, these two plugins seem to serve the same purpose. Can anyone provide insight as to why this is? ...

Implementing dynamic form fields in Angular 2 to efficiently store user input in a database

Currently, I am involved in a project using Angular 2. The task is to include fields with data from the database (specifically rows with the field value 'test8'). If users want to add new fields and values, they need to click the "Add new row" bu ...

Is there a way to retrieve the initial item of a JSON array from an HTML document using Angular 2?

Within the src/assets/ directory, I have a json file called product.json with the following structure: [ { "images": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png", "textBox": "empty", "comments": "empty" }, { "i ...