Angular2 ERROR: Unhandled Promise Rejection: Cannot find a matching route:

I'm facing an issue with my Angular2 application while utilizing the router.navigateByUrl method. Within my component, there is a function named goToRoute, structured as follows:

router.goToRoute(route:string, event?:Event):void {
        if (event) {
            if (event.defaultPrevented) {
                return;
            }
            event.preventDefault();
        }

        this.router.navigateByUrl(route); // adding '/' before route does not work...
        // close the menu if it was open and clicked!
        if (this.menuOpen) {
            this.toggleHamburger();

} }

I typically use this function within an ngFor loop in my HTML like so...

<div *ngFor="let route of routes ">
    <div (click)="goToRoute(route.path, $event)"> {{ route.display }} </div>
</div>

However, upon clicking a div, I encounter the following error:

EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: 'about-us'
zone.js:461 Unhandled Promise rejection: Cannot match any routes: 'about-us' ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot match any routes: 'about-us'(…)consoleError @ zone.js:461_loop_1 @ zone.js:490drainMicroTaskQueue @ zone.js:494ZoneTask.invoke @ zone.js:426
zone.js:463 Error: Uncaught (in promise): Error: Cannot match any routes: 'about-us'(…)

This confusion arises even though my routes include the following (where DisplayRoutes is a custom type extending the Route object):

export const routes:DisplayRoutes = [
    {
        path: '',
        display: 'Home',
        component: HomeComponent
    }, {
        path: 'about-us',
        display: 'About us',
        component: LeftSubNavigation,
        index: {
            component: DetailMoreLayout
        },
        children: [
            {
                path: ':id',
                component: DetailMoreLayout
            }
        ]
    }, {
        path: 'teams',
        display: 'Teams',
        component: LeftSubNavigation,
        index: {
            component: DetailMoreLayout
        },
        children: [
            {
                path: ':id',
                component: DetailMoreLayout
            }
        ]
    }
];

As evident, there is indeed a route named 'about-us'! Still, for some reason, the paths fail to align. When logging the route and event passed to the goToRoute method, the output looks like this...

about-us MouseEvent {isTrusted: true, screenX: 1809, screenY: 382, clientX: 42, clientY: 144…}

Currently making the transition from "@ngrx/router": "^1.0.0-beta.1" to

"@angular/router": "3.0.0-beta.2"
. Although there is a base tag, things seem to malfunction when employing router.navigateByUrl. The same issue arises with deep linking, like when accessing http://localhost:4200/about-us directly in the browser.

Your insights or recommendations are welcomed.

Answer №1

Remember to include a prefix '/' in your route path.

If the route 'about-us' has child routes, make sure to define an empty path for it. This will allow it to redirect to any existing routes.

{path: '', redirectTo: 'other-path', pathMatch: 'full'}

Also, ensure that your extension handles the display and index var in the config since they are not included in the default Routes type.

Check out the official tutorial for more information.

For further guidance on using multi-level routing, refer to this Stack Overflow question: multi level routing.

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

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

Guide on translating text in Angular Material Snackbar using ngx translate

I have successfully integrated ngx translate into my project, allowing me to convert text on HTML pages into different languages using JSON files. However, I am facing a challenge in changing the language of the text displayed in the "Snackbar" component i ...

Unable to locate the module 'next' or its associated type declarations

Encountering the error message Cannot find module '' or its corresponding type declarations. when trying to import modules in a Next.js project. This issue occurs with every single import. View Preview Yarn version: 3.1.0-rc.2 Next version: 1 ...

I've added a check, so why is TypeScript still complaining about the possibility of my property being undefined?

const handleLinkClick = (index: number) => () => { const hasUrl = !!searchItems[index]?.url; if (hasUrl) { navigateToLink(searchItems[index]?.url); } else { setItemSelected(index); } }; However, the issue I encountered is: (property) ...

What is the best way to incorporate the trix-editor into an Angular 2 application?

I've been struggling to incorporate the Trix editor into my Angular application. I can't seem to find any resources or npm packages that explain how to install the Trix editor in an Angular 2 app. Can anyone provide guidance on where to find the ...

Angular bootstrap search is encountering an issue with locating a supporting object. It seems to be struggling to find a differ for the object of type 'object'

I recently delved into learning autoComplete Search. While I successfully retrieved the object from the backend server, displaying them in HTML resulted in the following error. NgbTypeaheadWindow.html:5 ERROR Error: Cannot find a differ supporting object ...

Encountering an Issue with the Development Server in React and TypeScript

My attempt to set up a new TypeScript-React project using the command npx create-react-app todo-list --template typescript was successful in terms of installation. However, when I tried to run the project with npm start I encountered the following error: ...

Struggling to access the 'payload' property of an undefined object? In TypeScript, you can easily bind and access JSON objects using *ngFor directive

I've been attempting to retrieve highscores from the server using node angular and making an http request. Although I successfully obtain the JSON file from the server, I am encountering difficulty accessing the fields for processing in the *ngFor lo ...

Issue encountered while attempting to initiate a new project with Angular CLI

Encountering an error while trying to create a new app using Angular CLI Attempted solutions: npm cache clean --force npm cache verify Unfortunately, the above steps did not resolve the issue Please refer to the image linked below https://i.sstatic.ne ...

Guide for building a Template-driven formArray in Angular

I am currently implementing a fixed number of checkboxes that are being bound using a for loop. <ul> <li *ngFor="let chk of checkboxes"> <input type="checkbox" [id]="chk.id" [value]="chk.value&q ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Error TS2339: Cannot access attribute 'reactive_support' on interface 'LocalizedStringsMethods'

Encountering the error TS2339: Property 'reactive_support' does not exist on type 'LocalizedStringsMethods' I recently updated TypeScript from version 2.6 to 2.9, and attempted import LocalizedStrings from 'react-localization&apo ...

Angular 13: Masking User Input with Reactive Form Controls

Looking to incorporate a phone number input field with formatting in a reactive form. The desired format is (123) 456-7890. For reference, check out this example link: https://stackblitz.com/edit/angular13-reactive-form-validation-y1qwmf?file=src/app/app. ...

"Utilizing TypeScript with React: Creating a window onClick event type

My linter is not happy with the any type for window.onClick. What should be the correct type? import React, { useContext, useState } from 'react'; import { Link } from 'react-router-dom'; import { Global } from '../globalState&apo ...

Animating the Click Event to Change Grid Layout in React

Can a grid layout change be animated on click in React? For instance, consider the following component: import { Box, Button, styled, useMediaQuery } from "@mui/material"; import Row1 from "./Row1"; import React from "react"; ...

Obtain the hexadecimal color code based on the MUI palette color name

Is there a way to extract a hexcode or any color code from a palette color name in Material UI? Here is my use case: I have a customized Badge that I want to be able to modify just like the normal badges using the color property. The component code looks ...

Is there a way to trigger a request to the backend when the user closes or refreshes the browser?

My Objective: I am working on a lobby feature that updates automatically when a player leaves. Using backend requests and sockets, the lobby is updated to display the current list of players after someone exits. The Challenge: I am faced with the issue ...

"Encountering a Server Error when attempting to refresh routing children

My project is hosted on a subDirectory server with Apache. The base index for my project can either be <base href="./"> or <base href="/myFolder/">. The issue arises when I am on a child route page, for example: www.mysite ...

When changing the dropdown option on a separate page in React/Next JS, all checkboxes show the clicked style as a result of utilizing useState

I have implemented checkboxes for three different categories: "Types", "Price", and "Categories". They function correctly, with data being passed to a separate checkbox component without any issues. The problem arises when I click a checkbox and then inte ...

Removing an element from the array stored in NGRX

I currently have an object stored in a repository in the following format: export interface Referential { id: string; values: Array<ReferentialData>; } export interface ReferentialData { libelle: string; value: string; borderColor: string; ...