Error in Angular 7: ActivatedRoute paramId returns null value

On page load, I am trying to subscribe to my paramsID, but when I use console.log(), it returns null. I am currently working with Angular 7.

Here is my TypeScript code:

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from "@angular/router";
    @Component({
     selector: 'c:navbar',
     templateUrl: './navbar.component.html',
     styleUrls: ['./navbar.component.scss']
    })
    export class NavbarComponent implements OnInit {
     selectedItem: string;
     selectedFlag: string;
     paramsId: any;
    constructor(private _ActivateRoute: ActivatedRoute) { }

    ngOnInit() {
    this._ActivateRoute.paramMap.subscribe(params => {
    this.paramsId = params.get("activeLang");
    console.log('Get Param',this.paramsId);
    });
   }

This is my route setup:

   import { NgModule } from '@angular/core';
   import { Routes, RouterModule } from '@angular/router';
   import { HomePagesComponent } from './pages/home-pages/home- 
    pages.component';
   import { PersonalPagesComponent } from './pages/personal- 
    pages/personal-pages.component';


   const routes: Routes = [
  {path: '', redirectTo: 'en/home', pathMatch: 'full'},
  {path: ':activeLang/home', component: HomePagesComponent},
  {path: ':activeLang/personal', component: PersonalPagesComponent},
  {path: ':activeLang/business', component: BusinessPagesComponent},
   ];

   @NgModule({
   imports: [RouterModule.forRoot(routes, {scrollPositionRestoration: 
             'enabled'})],
   exports: [RouterModule]
   })
   export class AppRoutingModule { }

I am unsure if my code is correct because null is being returned when I use console.log(). Can someone help me troubleshoot this issue?

The expected result should be the output of "en" in the console.

Answer №1

Here is a suggestion to consider:

Assign the value of this._ActivateRoute.snapshot.paramMap.get("activeLang") to this.paramsId.
Then, log this.paramsId to the console.

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

Ensuring Koa ctx.query is valid prior to invoking the handler function

I'm currently working on a basic route that looks like this: router.get('/twitter/tweets', async (ctx) => { const { limit, page, search } = ctx.query ctx.body = { tweets: await twitter.all(limit, page, search), } }) The issue I ...

Tips for avoiding the influence of the parent div's opacity on child divs within a Primeng Carousel

I'm struggling to find a solution to stop the "opacity" effect of the parent container from affecting the child containers. In my code, I want the opacity not to impact the buttons within the elements. I have tried using "radial-gradient" for multipl ...

Utilizing Node.js Functions for Sharing Database Queries

When it comes to sharing DB query code among multiple Node.js Express controller methods, finding the best practice can be challenging. Many samples available online don't delve deeply into this specific aspect. For instance, let's consider a ge ...

Experiencing an Issue with NGINX Loading Vue 3 Vite SPA as a Blank White Page

I currently have the following NGINX configuration set up: events { worker_connections 1024; } http { server { listen 80; server_name localhost; location / { root C:/test; index index.html; ...

Ways to cancel a subscription once a specific parameter or value is met following a service/store interaction

I am working with a service that provides a changing object over time. I need to unsubscribe from this service once the object contains a specific property or later when the property reaches a certain value. In situations like these, I typically rely on t ...

Displaying JSON Object in Kendo UI Grid with Incorrect Format

I encountered an issue where a function that I passed to a Kendo Grid field in the fetch method returns perfectly on console.log, but only [object Object] is returned in the Kendo Grid display. Here's the background: I am utilizing two services - Rev ...

Unable to access or modify properties within a function passed as an argument

deleteDialog(item, func: Function) { this.dialogService .open(ConfirmDialogComponent, { context: { title:"Are you sure?", cancelClss: "info", confirmClss: "danger", }, ...

Incorporate an image icon into an Angular grid

Currently, I am in the process of building a web application using Angular. The main goal is to create a grid and color specific cells based on data input. Below is the snippet of my HTML code: <mat-grid-list cols="10"> <mat-grid-tile * ...

Error message: "react-router typescript navigation version 0.13.3 - Unable to access 'router' property"

I'm currently in the process of porting an existing React project to TypeScript. Everything seems to be going smoothly, except for the Navigation mixin for react-router (version 0.13.3). I keep encountering an error message that says "Cannot read prop ...

An effective way to retrieve a property from an observable by utilizing a pipe

I'm having trouble storing an OrderState object in my ngrx store and extracting data from it for my UI using the async pipe. Specifically, I want to retrieve a child property from this observable object. order.state.ts export interface OrderState { ...

Are there any other methods besides @ViewChild to access template elements by template ID in Angular v4.3.3?

In the past, using @ViewChild('#templateId') was an accepted method for obtaining an Element Reference. @ViewChild('#templateId') elementName: ElementRef; However, it appears that this is no longer a viable approach as @ViewChild now ...

`Browser Extension Compatibility``

I am currently working on developing a TypeScript extension that is compatible with all major browsers. I have come across the package https://www.npmjs.com/package/web-ext-types which I have integrated into my package.json file. While coding in TypeScrip ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

The specified property is not found in the type 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }>'

As I delve into utilizing React along with TypeScript and Material-UI components, I encounter some errors. One such error message pops up like this: The Property 'openToYearSelection' is not found on type 'IntrinsicAttributes & Intr ...

You need to provide 1 type argument(s) for the Generic type ModuleWithProviders<T> in Angular 10 Swagger Codegen

Currently, I am generating Codegen proxies using . Upon implementing this in Angular 10, I encountered the following error. How can this issue be resolved? The error message reads: 'Generic type 'ModuleWithProviders' requires 1 type argume ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Drawer in Material-UI has whitespace remaining at the corners due to its rounded edges

While using the Material UI drawer, I attempted to round the corners using CSS: style={{ borderRadius: "25px", backgroundColor: "red", overflow: "hidden", padding: "300px" }} Although it somewhat works, the corners appear white instea ...

Retrieve the input type corresponding to the name and return it as a string using string template literals

type ExtractKeyType<T extends string, K extends number> = `${T}.${K}`; type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends readonly unknown[] ? ExtractKeyType<Key, 0 | 1> : T[Key] extends Record<str ...

limitation on pairings of two generic types

How can I specify in TypeScript that "You can pass in any two objects, as long as their combination satisfies type X"? For example, consider the following function: function myFunction(options: {x: number, y: string}){ } Now, let's say we have anot ...

What is the best way to specify a type for an object without altering its underlying implicit type?

Suppose we have a scenario where an interface/type is defined as follows: interface ITest { abc: string[] } and then it is assigned to an object like this: const obj: ITest = { abc: ["x", "y", "z"] } We then attempt to create a type based on the valu ...