The mystery of Angular 2: Unveiling why ActivatedRoute.params always returns an empty object

I've been facing an issue with accessing the :id route parameter in a router guard. It seems to always return an empty Object{}.

Initially, I was unsure of how to approach this problem, so I referred to this question for guidance. However, it didn't provide a solution as my problem lies within a guard.

Here's a snippet from my route declaration in app-routing.module:

const dashboardRoutes: Routes = [
    {
        path: "dashboard/:id",
        component: dashboard.DashboardComponent,
        canActivate: [guard.LoggedInGuard],
        children: [
            {
                path: "",
                redirectTo: "home",
                pathMatch: "full"
            }, 
            ...

And here's part of my guard code located in existsInDatabase.guard (I attempted using both params & queryParams):

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

canActivate() {
    console.log(this.activatedRoute.params);
    this.activatedRoute.params.subscribe(param=> {
        console.log(param); // outputs an empty Object{}
        console.log(param['id']); // shows undefined
    });
    this.activatedRoute.queryParams.subscribe(param=> {
        console.log(param); // produces an empty Object{}
        console.log(param['id']); // gives undefined
    });
    return true;
}

The issue arises when transitioning from

http://localhost:4200/dashboard/136364285

to:

http://localhost:4200/dashboard/136364285/dock/1654321

How can I successfully retrieve 136364285?

Answer №1

After encountering a similar obstacle, I was able to overcome it by implementing the following solution within my guard's canActivate function.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    console.log(route.params['id']); // logs 783745921
    return true;
}

Initially, I mistakenly only had access to route: ActivatedRouteSnapshot in the constructor and using .snapshot did not provide the expected outcome. Now, by accessing the upcoming route, I am able to correctly obtain the desired parameters.

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

Encountering a d3.js runtime issue following the transition to Angular 8

I've been experimenting with upgrading my Angular 6 application to Angular 8. It compiles fine, but I'm facing a runtime error as soon as it runs: "d3.js:8 Uncaught TypeError: Cannot read property 'document' of undefined". The specific ...

Why am I encountering a 400 error with my mutation in Apollo Client, when I have no issues running it in Playground?

After successfully testing a mutation in the playground, I attempted to implement it in my Apollo client on React. However, I encountered an error message stating: Unhandled Rejection (Error): Network error: Response not successful: Received status code 40 ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

Having trouble with @viewChild not activating the modal popup and displaying an error message stating that triggerModal is not a function in

I am facing an issue where the click event is not being triggered from the parent component to display a Bootstrap 3 modal. I am getting the following error: ERROR TypeError: this.target.triggerModal is not a function This is what I have done so far: Pa ...

Angular: Eliminating code duplication through service transfer

One code snippet that I frequently use when booting the app is (ngOnInit): this.route.queryParamMap.subscribe( params => { const id = params.get('id'); if (id) { this.contactsService.GetContactByUserId(id) .subscribe( ...

Angular material mat-calendar multiyear range selection视图

Experiencing an issue with a mat-calendar multiyear view. By default, the dropdown multiyear table displays 3 years back and 20 years forward from the current year (2016, 2017....2030). https://i.sstatic.net/tWSif.png Instead, I am looking to view 23 yea ...

Creating a dynamic form with Angular 5 that includes a conditional required textarea

When the checkbox is clicked, a textarea will appear and is required [required]="otherVendorsChecked == true ? true : false". Even if I select the checkbox and then deselect it, the textarea input remains required. Any ideas on what could be going wrong? ...

Tips for creating a typescript module definition that exports a module dependency as one of its members

Let's consider a particular situation: I am in the process of creating typescript definitions for two commonJS modules, A and B. Module B has a dependency on module A, and to make things easier, B directly exports A as a property B.A so that users do ...

Resetting the value of a radio button input option to null using Angular2 ngModel

In my Angular2 application, I am attempting to implement radio button inputs using ngModel and value. The goal is to have three options: true, false, and null. However, I am struggling to assign a value of null to one of the inputs. Ideally, when nothing ...

The creation of a Firebase user account with the specified email and password

I'm currently facing an issue while creating a new user with email and password using firebase authentication. The problem arises when I try to access the displayName from the returned async call before the updateProfile function, as it returns a null ...

Encountering a type 'any' issue with the Authentication guard injection in Angular 17

I implemented a functional guard in Angular 17 import { Inject } from '@angular/core'; export const checkoutGuard: CanActivateFn = (route, state) => { const customerService = Inject(CustomerService); const router = Inject(Router); ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

Can someone share with me the best practices for implementing @HostListener within a method in my Angular 16 project?

Currently, I've been involved in developing a Single Page Application using Angular 16, TypeScript, and The Movie Database (TMDB). My task at hand is to implement the "infinite scroll" functionality on a particular component. To achieve this, I have ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

The code encountered an error when trying to access the property 'template' of an undefined variable in the MatRowDef.push

I am encountering an issue with Angular lazy loading. Whenever I switch from one child component to another, I receive an error in a component where I have implemented a mat-table for displaying data. Error: TypeError: Cannot read property 'template& ...

Enhance TypeScript class declarations with additional properties

Our company has developed its own test framework for our software because we found it difficult to use an open-source framework within the context of our specific development needs. Recently, I took on the task of creating Typescript Definition Files to e ...

Error: Attempting to access the value property of a null object within a React Form is not possible

I am currently developing a form that includes an HTML input field allowing only numbers or letters to be entered. The abbreviated version of my state interface is outlined below: interface State { location: string; startDate: Date; } To initiali ...

Simultaneous asynchronous access to a single object

I have been working with JS/TS for quite some time now, but the concept of race conditions still perplexes me. I am currently attempting to execute the following logic: class Deployer { protected txDataList: Array<TXData>; constructor() { this ...

Coverage of code in Angular2 using Qunit

Is there a reliable code coverage measurement tool or framework that can easily be integrated to assess the code coverage of Angular2-TypeScript code with QUnit tests? I have come across some frameworks like remap-istanbul, blanket.js etc., but these fram ...