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

Mapping an array based on its individual values

How can I sum values in an array of objects based on a specific condition? [{amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}] Is there a method to map and calculate t ...

What is the best way to configure Apache to act as a reverse proxy for an ASP.NET Core API and an Angular

My aspnet core api is running on localhost:8080 (kestrel) and functions perfectly on localhost:80 (apache reverse proxy), making it accessible from the internet via www.example.com. I am looking to deploy my angular client on the same port locahost:80(www ...

Design a unique login portal separate from all other website pages

I'm a beginner with Angular and I'm currently working on creating a login page. My issue is that I want the login page to be the only component displayed initially, and once the response is 200, I want to redirect to another component. Here&apos ...

Addressing command problems in Angular

I am experiencing an issue with a dropdown functionality. When a user selects an option and then presses either the "Delete" or "Backspace" button on the keyboard, the value from the dropdown clears which is working correctly. However, I am attempting to i ...

Struggling to incorporate method decorators to handle http errors in Angular?

My goal is to implement error handling for all http requests using custom decorators. Here's my current code snippet: createRecord(data: data) { return this.httpClient.post(`${this.apiURL}/record/`, data); } I am looking to refactor thes ...

Interfaces in Typescript

In my Angular 2 project, I am working on creating an interface for a complex object. Here is the code snippet of the object: // Defining the render state object this.aRenderState = { model: "", colour: false, showWireframe: false, showGrid: true, ...

Exploring the potential of Angular2's WebSocket service by efficiently accessing the parent component

I need some assistance with implementing WebSockets in my angular2 application. However, I've encountered a minor issue that I can't seem to solve. Here's what I have so far: I've created a service that has a method for creating a WebS ...

Tips for retrieving data from Angular Material Table source

It's great to see everyone doing well! I'm facing an issue with rendering data to a material table, and I can't figure out why it's not working. When I try to assign the data to the table's datasource for rendering, the information ...

Using Angular - Executing a query only when a URL parameter is present

Can I execute this query only if a URL parameter (paramOne) is present? queryAndSubscribe(){ this._subscription = this._activatedRoute.params.pipe( tap (params => { console.log('params = ', params); }), switchMap ...

Troubleshooting the issue of having multiple menu items in Material UI

Every time I attempt to add the Menu component multiple times, I encounter an issue with the popup list displaying incorrectly. To demonstrate this problem, you can view it through the link provided on codesandbox below. I have included data-id attributes ...

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 ...

angular ngFor directive for displaying items in an array or a single element

In an angular 7 application, custom components are utilized with a common pattern where child components can expect either a single value or an array. The component's layout is determined based on a flag. Is there a way to simplify this pattern so tha ...

Unable to implement client-side functionalities in Angular 17 with server-side rendering

view image description hereview image description here Is there a way to make my component run on the client side, similar to "use client" in Next.js? This is my first time working with server-side rendering in Angular, and everything works fine when it&a ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...

Encountering a TypeError while trying to use the select function with the userQuery in Angular v16 and Akita

Upon upgrading from Angular v11 to v16, Akita is causing errors in my Angular project main.js:23 ERROR TypeError: this.userQuery.select is not a function at main.js:1:262487 at u.<computed> (polyfills.js:23:32704) at A.invokeTask (polyfil ...

Ways to decrease the space between lines of text within a single mat-option element

::ng-deep .mat-select-panel mat-option.mat-option { height: unset; } ::ng-deep .mat-option-text.mat-option-text { white-space: normal; } Currently, I have implemented this code to ensure that text in options wraps to the next line when it's too ...

I encountered an issue with Cypress when attempting to utilize a custom command. The error message "TypeError cy.login is not a function" keeps popping up. Any suggestions on how to resolve this

I am currently working on a TypeScript project and I am attempting to write some tests using Cypress. However, I encountered the following error: TypeError - cy.login is not a function. This error occurred during a before each hook, so we are skipping the ...

Using template references in ViewChildren

I'm facing an issue trying to utilize ViewChildren to create a QueryList from TemplateRef, but I am unable to pass it to the input component. For instance: Component.ts: @ViewChildren(TemplateRef) cellTemplates: QueryList<TemplateRef<any>& ...

When passing e: EventTarget as a forwarded prop through a wrapper component, Typescript raises an error about the missing "value" property in the onChange function

In my project, there is a custom component called SelectField that serves as a wrapper for rendering label, helper text, and select input (inspired by TextField from @material-UI). The SelectField component exposes props like value and onChange, which are ...

What led the Typescript Team to decide against making === the default option?

Given that Typescript is known for its type safety, it can seem odd that the == operator still exists. Is there a specific rationale behind this decision? ...