Create a variable that is assigned the value of a route parameter, but leave it undefined if the parameter cannot be

I am working on an Angular 7 component where I extract a route parameter value:

export class PostComponent implements OnInit {

  postId: number;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {

    console.log(this.postId);

    this.route.paramMap.subscribe(parameters => {
      this.postId = +parameters.get('postId');
    })

    console.log(this.postId);

  }

}

In the initial Console Log, postId is undefined as expected.

In the subsequent Console Log, postId reads as 0 since it's not present in the URL.

I aim to maintain postId as undefined if it's absent from the URL. How can this be achieved?

Answer №1

A great way to achieve this functionality is by utilizing the following code snippet:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      const postId = params['postId'];
      const postIdToUse = postId ? +postId : undefined;
      console.log('Received PostId as:', postIdToUse);
    });
  }

}

Check out this Working Sample StackBlitz for reference.

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 causes TypeScript 3.7.5 to trigger an error while typing a function that accepts an array as a parameter?

I'm facing a perplexing compiler error while trying to define a function that requires an array as its sole argument. Below is a concise scenario to reproduce the issue: http://www.example.com import React from 'react' type FooProps = { ...

How can you set up multiple router-outlet instances in Angular without explicitly naming them in the routing configuration?

As an illustration, in this particular project showcased at this link, The functionality of multiple routing is functioning as intended. However, upon clicking the Product Link, the URL shifts from: to I am looking to eliminate the addition of (sidebar: ...

IdentityServer4: The authentication time is not specified

I'm currently working on an angular (asp.net core) application that utilizes an identityserver4 server for authentication. Initially, the login process works seamlessly, displaying the login form and returning both the id_token and access_token. How ...

Jhipster: Allowing users to effortlessly generate linked objects under their account

My goal is to develop a service that assists individuals in making informed decisions. To achieve this, I must guide users through an onboarding process where they create entities that reflect their circumstances. During data input, I aim to establish lin ...

Implementing angular material design to a particular element exclusively

Can I assign the angular material default theme to a specific component only? I tried: @import "~@angular/material/prebuilt-themes/indigo-pink.css"; In one of my component's .scss files and specified this as the styleUrl in the component.ts file. H ...

Leveraging TypeScript modules without the need for require()

I created a TypeScript 2.3 app called app.ts that requires the Vue.js library version 2. I manually added the Vue.js script src in the HTML file. All I wanted was to use Vue.js with type checking. I thought I could simply reference it like this: /// & ...

The @angular/cli ng serve command freezes after a period of activity

My experience with Angular development started with @angular/cli@5 and ng serve always ran smoothly. However, after updating to version 7.0.0 and creating a project with Angular 7.0.0, I encountered an issue where Angular stopped recognizing changes in fil ...

Utilizing Arrow Functions with Parameters in Angular

I am currently working on an Angular 4 app and I am attempting to create a queue of actions. Each action should only be executed after the previous one has finished, and each action should receive its own set of parameters. public activeRegistrationAndS ...

Encountering NoResourceAdapterError when using @admin-bro/nestjs alongside @admin-bro/sequelize and MySQL?

Encountering a similar issue with '@admin-bro/sequelize' NoResourceAdapterError: No compatible adapters found for the provided resource import { Database, Resource } from '@admin-bro/sequelize'; import { AdminModule } from '@admin- ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

Custom type declaration file in Typescript fails to function properly

I have searched through countless solutions to a similar issue, but none seem to work for me. I am attempting to utilize an npm package that lacks TypeScript type definitions, so I decided to create my own .d.ts file. However, every time I try, I encounter ...

React.Context is associated with a universal module definition global variable

I have just created a new context.tsx file containing the following code: import { createContext } from 'react'; export interface LibsAndComponentsInterface { data: unknown[]; } export const LibsAndComponentsContext = createContext< Libs ...

The program is throwing an error stating that the property 'user' is not found on the data type 'DefaultRootState'

Issue Encounter I am currently encountering the error message 'user' does not exist on type 'DefaultRootState'. I have attempted to resolve it without success so far. Here is the link to my GitHub repository. Error Details C:/Users/t ...

Although the FormGroup itself is considered ng-invalid, the FormControls within the nested FormGroup are still ng-valid

I am dealing with a nested form group called 'grades': Even though the nested form group 'grades' is marked as ng-invalid, the child form controls are actually marked as ng-valid. Why isn't the invalid status of the nested form b ...

Issue with Angular 4: Module not found after creation

Recently, I created a basic module using ng called "core" in my app folder. It is located at the same level as app.module. However, when I attempt to utilize it from app.module.ts, I encounter an error stating 'Cannot find module' import { CoreM ...

Is it necessary for a TypeScript Library's repository to include the JavaScript version?

Is it necessary to include a JavaScript version of the library along with the Typescript repository for consumers? Or is it best to let consumers handle the compilation process themselves? Or should I consider another approach altogether? ...

The child component notifies the parent to update itself, then the parent proceeds to update the input value of another child

This question may have been asked numerous times before, but despite trying various approaches such as using a subscription on the child component and ngOnChanges, I am still unable to get it to work. Here is the basic structure of the issue in my project ...

Using TypeScript to create a list of object keys defined as [key: string] key/value pairs

I'm looking to define an interface in TypeScript, but I'm unsure of how to go about it. Here's what I have in mind: export interface SomeInterface { testProp:{ [key: string]: { prop1: string; prop2?: string; prop3?: string; ...

Include a new course based on a specific situation

Is it possible to conditionally add a specific class using vue js? In my DataStore, I have two values defined in TypeScript: value1: 0 as number, value2: 0 as number Based on the values of value1 and value2, I want to apply the following classes in my te ...

dynamically open ngx-bootstrap accordion panels

I implemented the ngx-bootstrap accordion feature to display a list of blog posts. Below is the template structure: <accordion id="blog-list"> <accordion-group *ngFor="let post of posts; let first = first;" [isOpen]="first" id="post-{{post.i ...