Angular2: Validating routes with integer parameters

Take this router as an example:

{
    path: '/client',
    component: ClientRootComponent,
    children: [
        {path: '', component: ClientListComponent},
        {path: ':clientId', component: ClientOpenComponent, resolve: makeResolver(ClientOpenResolver)}
    ]
},
{
    path: '**',
    component: NotFoundComponent
}

In this case, both URLs /client/1234 and /client/asdf will be directed to ClientOpenComponent. Is there a way to ensure that /client/asdf is handled as a NotFound situation and redirected to the NotFoundComponent instead?

Answer №1

To customize your route matching, you can create a custom matcher as shown below:

import { defaultUrlMatcher } from '@angular/router/src/shared';

function digitsMatcher(segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult | null {
  const result = defaultUrlMatcher(segments, segmentGroup, route);

  if (!result || !result.consumed || result.consumed.length < 1) {
    return;
  }

  const re = /^\d+$/;
  const match = re.exec(result.consumed[0].path);

  if (match) {
    return result;
  }

  return null;
}
{
    path: '/client',
    component: ClientRootComponent,
    children: [
        {path: '', component: ClientListComponent},
        {path: ':clientId', component: ClientOpenComponent, resolve: makeResolver(ClientOpenResolver), matcher: digitsMatcher}
    ]
},
{
    path: '**',
    component: NotFoundComponent
}

Note that this code has not been tested yet.

For more information, check out the following resources:

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 reason `addEventListener` does not work with a class method?

Recently, I discovered that the listener passed to addEventListener can actually be an object with a handleEvent function instead of just a callback function (here). However, I encountered an issue when trying to use handleEvent as a class method: class F ...

Understanding how to infer the type of a function when it is passed as an argument

Looking at the images below, I am facing an issue with my function that accepts options in the form of an object where one of the arguments is a transform function. The problem is that while the type of the response argument is correctly inferred for the e ...

What is the best way to create props that can accommodate three distinct types of functions in TypeScript?

I have been encountering a problem with the last function in my props interface that is supposed to support 3 different types of functions throughout the application. Despite adding parentheses as requested, I am still facing errors. // In Parent compon ...

Angular 6 presents a challenge in rendering data within the multi select drop down feature

I am currently utilizing a multi-select library called ng-multiselect-dropdown in my Angular v6 project. Unfortunately, when I try to display my list using the multiSelect feature, the drop-down shows a message saying "No data available". I discovered th ...

Is there a way to assign a function signature to every property within a class in typescript?

When I am structuring a class to contain all methods related to its functionality, I ensure that all the methods within the class have a specific signature. I attempted to utilize an index signature in this manner: interface rulesType { [key:string]: t ...

A critical error has occurred: RangeError - The maximum call stack size has been exceeded while trying to

After attempting to filter a list of titles using Ng2SearchPipeModule, I imported the module in app.module.ts and created a new searchbar component. searchbar.component.ts import { FirebaseService } from './../../firebase.service'; import { Ang ...

Can multiple modules that are lazily loaded be active at the same time?

We're excited about our upcoming project that will feature a tab-based UI design. Each tab will represent a different feature module, loaded lazily to improve performance. Our goal is to allow users to switch between tabs seamlessly and keep previousl ...

Mastering regular expressions in TypeScript

My goal is to perform linting on staged files that are either .ts or .tsx and located within the src folder. I am aware that for selecting all js files one can use "*.js": [--list of commands--] inside the lint staged property. I'm curious to learn m ...

After installing TypeScript community stubs, WebStorm is unable to locate the module

Recently, I tried to incorporate the ramda library into my project and went ahead to install its TypeScript community stubs in WebStorm. https://i.stack.imgur.com/fCFG8.png Despite my efforts, I encountered an error that stated — Cannot find module &a ...

Troubleshooting: Socket.io integration in Angular is not functioning within a .then() statement

Upon running this code snippet in a component: const videoholder = <HTMLDivElement>( document.querySelector('#videoholder') ); const myPeer = new Peer(this.userid, { host: '/', ...

I am struggling to extract data from the spawned Node.js child process. What am I overlooking?

Trying to utilize a spawned command-line process for lzip in order to expand an lzipped data stream due to the lack of suitable native JavaScript tools. Succeeded in achieving this by working with files and file descriptors, although cumbersome to handle ...

Navigating the return types of Array shifts in Typescript 2.0 with rigorous null checks

In my project using Typescript 2.0 with strict null checks, I am working with an array: private _timers: ITimer[] and have the following if statement: if(this._timers.length > 0){ this._timers.shift().stop(); } However, I encounter a compile error ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Tips for configuring environment variables across multiple test files within Jenkins

In my random.test.ts file I am utilizing an environment variable: test.beforeAll(async () => { new testBase.BaseTest(page).login(process.env.EMAIL, process.env.PASSWORD); }) I want to execute my tests using Jenkins, but I am unsure of how to pass m ...

Encountering an issue with setting up MikroORM with PostgreSQL due to a type

I'm currently working on setting up MikroORM with PostgreSQL, but I've encountered a strange error related to the type: Here is the code snippet: import { MikroORM, Options} from "@mikro-orm/core"; import { _prod_ } from "./consta ...

What is the best way to configure eslint or implement tslint and prettier for typescript?

In my React/Redux project, I recently started integrating TypeScript into my workflow. The eslint configuration for the project is set up to extend the airbnb eslint configurations. Here's a snippet of my current eslint setup: module.exports = { // ...

Headers cannot be modified after they have been sent to the client in Node.js and Angular

I am working on developing login and registration services using Nodejs Express. Every time I make a request in postman, I consistently encounter the same error: https://i.stack.imgur.com/QZTpt.png Interestingly, I receive a response in postman (register ...

What are the steps to retrieve the original source code of an HTML file, specifically in Angular 2 RC4

Is there a way to retrieve the source code that I manually typed in my IDE using JavaScript? Note: I am working with angular2 rc4. I attempted to access it using Reflect.getMetadata, but encountered errors indicating that it is not functioning properly. ...

Automatic import feature for TypeScript components in Sublime Text 3

Currently, I am following an AngularJS beginner Tutorial while my mentor is using a different IDE. Personally, I prefer using SublimeText3 as I am more comfortable with it. One issue I face is that when I declare a new component in my app.module.ts (highl ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...