ERROR: Unhandled promise rejection: Route cannot be found. URL Segment: 'details'

My current setup involves a router configuration in my Angular application. Below is the code snippet showcasing my router settings:

import { Route, RouterModule } from '@angular/router';
import { ProjectDetailsComponent } from '../components/project-details/project-details.component';

export const ROUTES: Route[] = [
  {
    path: '',
    redirectTo: '/details',
    pathMatch: 'full'
  },
  {
    path: 'details/:id',
    component: ProjectDetailsComponent
  }
];

In addition to the router configuration, I also have a corresponding controller named ProjectDetailsComponent.

The routes have been registered in my app module as shown below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

// Custom components
import { AppComponent } from './app.component';
import { ProjectDetailsComponent } from './components/project-details/project-details.component';

// Routes
import { ROUTES } from './services/router';

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(ROUTES, { useHash: true })
  ],
  declarations: [AppComponent, ProjectDetailsComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Within my app.component file, I am attempting to redirect to the ProjectDetailsComponent using "/details" routes and passing along the project id:

import { Component, OnInit } from '@angular/core';
import { IProject } from './domain/projects
import { Router } from '@angular/router';
// Routes
import { ROUTES } from './services/router';

@Component({
    selector: 'projects-app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent implements AfterViewInit {
    public activeProject: IProject;
    public projects: Array<IProject>;

    constructor(public router: Router) {
    }

    ngOnInit() {
        this.router.navigate(['/details', this.activeProject.Id]);
    }
}

However, upon trying to navigate to the 'details/:id' route, an error is encountered:

C:\Sources\SolarPro\build\debug\resources\app\node_modules\@angular\core\bundles\core.umd.js:3521 EXCEPTION: Uncaught (in promise): 
   Error: Cannot match any routes. URL Segment: 'details'

I am seeking assistance in resolving this particular issue. Any guidance would be greatly appreciated.

Answer №1

The redirection is set to go to /information, but unfortunately, there is no defined component for it. It's essential to specify a component for the URL path /details.

routes.ts

export const NAVIGATION_ROUTES: Routes = [
  {
    path: '',
    redirectTo: '/details',
    pathMatch: 'full'
  },
  {
    path: 'details',
    component: DetailsComponent
  },
  {
    path: 'details/:id',
    component: ProjectDetailsComponent
  }
];

details.component.ts

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

  constructor(private router: Router) { }

  ngOnInit() {
    this.router.navigate(['/details', 1]);
  }

}

Answer №2

After trying various solutions, I finally managed to solve the issue that I was facing.

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['details']); // or redirect to default route
    }
  }
}

Angular 4 does not have a default route, so by handling errors you can redirect to the default route accordingly.

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

How to extract URL parameters in an Express.js and AngularJS web app

Encountering a routing issue in my ExpressJS and AngularJS project. This project is not a single-page application, and we are not utilizing any view engines like jade - only plain HTML. I am currently working on implementing password reset functionality ...

Mapped TypeScript type requiring scalar properties and allowing optional objects

I am in need of a TypeScript generic type that has the capability to alter another type so that all scalar properties (such as strings, numbers, booleans, etc.) remain mandatory, while object types become optional. For instance, given the User type below, ...

An issue occurred during the construction of an angular project: The Tuple type '[]' with a length of '0' does not contain any elements at index '0'

When I run the command ng build --prod, I encounter the following error: ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index &apo ...

Utilizing Angular's DomSanitizer to safely bypass security scripts

Exploring the capabilities of Angular's bypassSecurityTrust* functions has been a recent focus of mine. My objective is to have a script tag successfully execute on the current page. However, I keep encountering issues where the content gets sanitized ...

The pipe in Angular 2.0.0 was not able to be located

Error: Issue: Template parse errors: The 'datefromiso' pipe is not recognized Custom Pipe: import {Pipe, PipeTransform} from "@angular/core"; @Pipe({ name: 'datefromiso' }) export class DateFromISO implements P ...

Error TS2339: The code is trying to access a property 'f' that is not defined within the 'ReactiveComponent' type

I have recently started working with Angular and I encountered an issue while creating a reactive form. The form is supposed to display the submitted values in an array, but when I added validators to the password field, an error popped up. error TS2339: ...

Tips on utilising the datepicker solely with the calendar icon, avoiding the need for any input fields

I'm currently working on a Datatable filter and I would like to incorporate a calendar icon to facilitate date filtering by simply clicking on the Datatable Header. At this stage, I've managed to display a calendar Icon on my Datatable header, b ...

Issue encountered when assigning a CSS class to Angular component

My module contains a table structure with specific components. Here is the source code for table.component.html: <table border=1> <theader></theader> </table> The source code for theheader.component.html is as follows: <thea ...

Retrieve the initial token from a union, referred to as an "or list," in Typescript

Is there a way to define a generic type F with the following behavior: type X = F<'a'|'b'|'c'> should result in X being 'a'. And if type X = F<'alpha'|'beta'|'gamma'|'del ...

Leverage the power of npm to utilize various javascript libraries for

I seem to be a bit confused here. Currently, I have the following code snippets: import * as angular from 'angular'; import 'ts-angular-jsonapi'; Interestingly, no errors are being returned with this setup. But as soon as I try this: ...

Preventing duplicate actions on a Subject with Angular 7's rxjs debounceTime operator

While working on an Angular7 application, I encountered an issue where the KeyUp event of a numeric input was being captured by this specific HTML code: <input fxFlex type="number" formControlName="DM" (keyup)="changeDM()"> </div& ...

"Creating a visual representation of models exchanged between the client and server through Rest

Currently, I am working on a project that involves client-server communication via rest API, with Angular 2 calling restful web services as the primary method. The client side is written in Typescript, which is a subset of JavaScript. My main challenge li ...

Is there a way to turn off TypeScript Inference for imported JavaScript Modules? (Or set it to always infer type as any)

As I attempt to utilize a JS module within a TypeScript File, I encounter errors due to the absence of type declarations in the JS module. The root cause lies in a default argument within the imported JS function that TypeScript erroneously interprets as ...

Error message for invalid form control not displayed when value is assigned to form control in Angular

I am currently working with this editor: <div id="editor"></div> which sets its value to a form control. this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)` <div *ngIf="FrmGroup.get('name').inv ...

Leveraging *ngIf in conjunction with routerLink

How can I apply "ngIf" to a routerLink instead of using a button? For example: *ngIf="auth.isAuthenticated()" (click)="auth.logout()" Using: <a [routerLink]="['/']">Logout ...

How can I properly containerize an Express Gatsby application with Docker?

SOLUTION: I am currently working on a project involving an express-gatsby app that needs to be built and deployed using GitHub Actions. To deploy it on Heroku, I have learned that containerizing the app is necessary. As a result, I have created a Dockerfil ...

Errors from NestJS microservice class validator are visible in the docker container but do not appear in the API response

Seeking assistance with displaying validation errors in my NestJS project using class validator. This is my first time working with microservices and NestJS, as it's for a school project. Errors from my 'user' microservice container are not ...

Creating an index signature in TypeScript without having to use union types for the values - a comprehensive guide

Is it possible to define an index signature with strict type constraints in TypeScript? interface Foo { [index: string]: number | string } However, I require the value type to be either number or string specifically, not a union of both types (number | ...

While attempting to reinstall the admob-free plugin via npm, I encountered an error stating that it was missing a package.json file

While developing an app using Ionic, I encountered an issue with the AdMob plugin not being installed correctly. Trying to resolve this, I attempted to reinstall the plugin multiple times but kept running into errors. Seeking help from various threads, I ...

A guide on organizing similar elements within an array using Angular

Could you assist me in grouping duplicate elements into separate arrays of objects? For example: array = [{key: 1}, {key: 5}, {key: 1}, {key: 3}, {key: 5}, {key: 1}, {key: 3}, {key: 2}, {key: 1}, {key: 4}]; Expected output: newArrayObj = {[{key: 1}, {key ...