Troubles encountered while fetching URL parameters in Angular 2

Currently in the process of setting up a confirmation email system for my Angular 2 application with a .NET Core 2 backend. The flow goes like this: user registers -> an email is sent to confirm their account -> they click the link -> they should be directed to an Angular component that is supposed to retrieve the userId and generated token. However, when I navigate to the URL

http://localhost:35000/confirm-email?token=CfDJ8OR7TVlXC69LsUgYal539cq4%2FcxvIXYoyaXcvLXQofMfK8d%2Bp6JE02IBATC49meM8bNSq9pgzq%2B7MspZLt7h1hfetLF2iVkXRkQZHFiJluhRpJbZ7kkafpyrbXjs82KFjkzVSOEDGV4sC6x4%2Bd0i0SXejfK%2F%2FpZgKTnOhdvB%2FwbLK5iauwdDXnjV7ZN7LHA0HInpvBPF2OOpdjJ%2FXicRLYLq5ic4Pz7SnXz0iwOTj4HJQIZAX%2FA1DqgvrPR6vuaOwQ%3D%3D&userId=5da26d4c-f737-481c-9142-affd89e8e9d6

This takes me to the confirm-email component as expected, but I'm having trouble properly reading the parameters token and userId - they always show up as undefined. Here's a simplified version of the code for my Angular component:

export class ConfirmEmailComponent implements OnInit {
    emailConfirmed: boolean = false;

    constructor(private userService: UserService,
        private router: Router,
        private activatedRoute: ActivatedRoute) { }

    ngOnInit() {
        this.activatedRoute.params.subscribe((params: Params) => {
          let token = params['token'];
          let userId = params['userId'];

          this.userService.confirmEmail(token, userId).subscribe(
            (data) => {
              this.emailConfirmed = true;
            });
        });
    }
}

Answer №1

In order to properly receive data passed through query parameters, you should be subscribing to activatedRoute.queryParams instead of params. This is because query parameters are used for passing data in the URL ('my-url?key=value') rather than predefined params ('my-url/:someParam'). Here's how it should be done:

this.activatedRoute.queryParams.subscribe((params: Params) => { //etc

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

What is the best method for displaying file size in a user-friendly format using Angular 6?

Imagine having this snippet in an HTML file: *ngFor="let cell of dateFormat(row)">{{cell | filesize}}</td>, where the dateFormat function looks like this: dateFormat(row:string){ var today = new Date(row[4]); let latest_date = this.date ...

Creating a custom Angular filter to group every 3 items within an iteration into a new div container

When attempting to organize three instances of app-story-preview within a wrapper div using a ngFor loop, I encountered the following code: <ng-template [ngIf]="stories.length > 0" [ngIfElse]="empty"> <cdk-virtual-scroll-viewport [itemSize ...

Backend serving an Angular application with Spring Security configuration

As I develop a web application using Angular for the frontend and Java for the backend (using technologies like Spring Boot, Spring Security, JWT), I am facing some confusion on how these components should work together. During development mode, everythin ...

Tips for updating an observable in Angular 6 following a POST request

One of the challenges I am facing is related to the table displaying ticket information. Users have the ability to add new tickets and send them to the backend. However, the issue arises when the table does not update automatically with the newly added tic ...

Updating data in Angular reactive forms using asynchronous dropdowns

I am currently developing an Angular application and have encountered an issue that I am unable to resolve by solely reading the documentation. One of the components in my application is responsible for displaying a form: https://i.stack.imgur.com/p5KEU. ...

Choose the appropriate NPM module platform for Angular development

My Angular application runs smoothly in Chrome, but encounters errors on Internet Explorer. The issue arises from the different distributions of NPM modules I install. For instance, within the kendo-angular-charts folder, we have: - dist |- cdn |- e ...

Retrieving Files from POST Request Body Using Node.js and Angular

Currently, I am developing a MEAN Stack application and facing an issue while handling a form that should allow users to upload a file upon submission. The process seems to work seamlessly on the client side; however, when I inspect the request body after ...

When combining Angular with Workbox, you may encounter a ChunkLoadError stating that the loading of a specific chunk was refused to execute due to mismatch

When I added Workbox to Angular for the first production deployment, everything worked smoothly. However, after updating a module, rebuilding Angular, and injecting Workbox again, I encountered an issue. Upon visiting the site, I noticed that the service w ...

What is the best way to invoke a method from a class in Angular testing when the class has a Router constructor?

Currently, I am in the process of creating a test case for my authentication service outlined below. AuthService.ts import {Subject} from 'rxjs'; import {User} from './user.model'; import {AuthData} from './auth-data.model' ...

What is the best way to combine routes from various modules?

app.module.ts ... imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule, RecipesModule ], ... app-routing.module.ts ... const routes: Routes = [ {path: '', redirectTo: &ap ...

Creating a text box that stands out by adjusting the length in Bootstrap

My webpage displays three text boxes, and I want to increase the size of one specific text box. Here is the code that I have tried: <div class="row"> <div class="col-md-3"> <mat-form-field (keydown.enter)="$event.preventDefa ...

Converting ASP .Net Core Dto's and Controllers into TypeScript classes and interfaces

My concept involves incorporating two key elements: Converting C# Dto's (Data-transfer-objects) into TypeScript interfaces to ensure synchronization between client-side models and server-side. Transforming ASP .Net Core controller endpoints into Typ ...

Send the index of the row to the event handler in the table of data

I am currently utilizing a data table component from PrimeNG and have the following template code: <p-column [style]="{'width':'40px'}"> <template let-col let-rowData="rowData" let-rowIndex="rowIndex" pTemplate type="body" ...

Creating a RESTful API with Express, Firestore, Cloud Functions, and TypeScript

In my quest to create a REST API for my app, I've been delving into tutorials on Firestore & Cloud Functions. Unfortunately, all the ones I've come across are either outdated or simply don't work. This has been quite frustrating for me a ...

Discovering a specific string within an array of nested objects

Seeking guidance on creating a dynamic menu of teams using JavaScript/TypeScript and unsure about the approach to take. Here is an example dataset: const data = [ { 'name': 'Alex A', 'agentId': '1225& ...

Animation in Angular stops working once the user logs into the system

After creating an animation that triggers when a social login fails, I encountered an issue where it was working in Chrome but not in Safari initially. However, after some time, the animation started working in Safari as well without me making any changes. ...

Looking to reallocate information, paginate, and sort each time a new row is added to the mat-table

In my application, I have a customized <mat-table> with an implemented addRow() function that adds a new row to the table using default values based on the data type. The challenge I'm facing is that each time a new row is added, I find myself ...

Error in Angular unit testing: Service property is not utilizing the value set by spyOnProperty

I am currently working on creating a negative test scenario for my AuthService. The specific test case involves verifying that a property in the constructor is set to null if the angularFireAuth does not return any data. While the positive test case is fun ...

Creating a TypeScript declaration for the Cypress configuration file

When attempting to transition a setup-helper file to a ts definition, I encountered the following error message: Property 'domainName' does not exist on type 'Config' The error is related to this specific line of code: const { domainNa ...

Retrieving Vue data from parent components in a nested getter/setter context

<template> <div id="app"> {{ foo.bar }} <button @click="meaning++">click</button> <!--not reactive--> <button @click="foo.bar++">click2</button> </div> </templ ...