Navigating with Angular: How to properly redirect to a 404 error page for nested routes

I have structured my Angular application so that each feature has its own feature-routing.module.ts. These modules are then imported into the main app.module.ts. However, I am facing an issue where the application is not redirecting to /select-fund when the path is empty.

app-routing.module.ts

const routes: Routes = [
  { path: '',   redirectTo: '/select-fund', pathMatch: 'full' },
  { path: 'translate',   component: TranslateComponent, pathMatch: 'full' },
  { path: '**', redirectTo: '/not-found', pathMatch: 'full' },
]; // sets up routes constant where you define your routes

// configures NgModule imports and exports
@NgModule({
  imports: [RouterModule.forRoot(routes,  { enableTracing: false })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    LoaderComponent,
  ],
  imports: [
    NotFoundModule,
    DashboardModule,
    SubscriptionModule,
    DataroomModule,
    TaxDocumentsRefreshModule,
    HttpClientModule,
    OnboardingModule,
    AppRoutingModule,
  ],
  providers: [
    ErrorHandleService,
    HttpClient,
    {provide: RouteReuseStrategy, useClass: RouteReusableStrategy},
    {provide: ErrorHandler, useValue: Sentry.createErrorHandler()},
    {provide: HTTP_INTERCEPTORS, useClass: HTTPForbiddenInterceptor, multi: true},
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

not-found-routing.module.ts every module's routing follows a similar structure.

const routes: Routes = [
  {
    path: '',
    component: LoggedOutLayoutComponent,
    children: [
      {
        path: 'not-found',
        component: NotFoundComponent
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class NotFoundRoutingModule { }

auth.routing.module.ts


const routes: Routes = [
 ... other routes
  ,{
    path: '',
    component: DashboardWideLayoutComponent,
    children: [
      {
        path: 'select-fund',
        component: SelectFundComponent,
        canActivate: [AuthGuard, GatingGuard],
      },
    ]
  },

Answer №1

Implement a few modifications

app-routing.module.ts

const routes: Routes = [
  { path: '',  
    children: [{
      path: '',
      loadChildren: () => import('UPDATE_YOUR_AUTH_MODULE_ROUTING_FILE_PATH/auth.routing.module.ts').then(m => m.AuthModule)
    }]
  },
  { path: 'translate',   component: TranslateComponent, pathMatch: 'full' },
  { path: '**', redirectTo: '/not-found', pathMatch: 'full' },
];

auth.routing.module.ts

const routes: Routes = [
 ... other routes
  ,{
    path: '',
    redirectTo: '/choose-fund', 
    pathMatch: 'full'
  },
  {
    path: 'select-fund',
    component: SelectFundComponent,
    canActivate: [AuthGuard, GatingGuard],
  }
}],

Answer №2

Perhaps a different approach could be more suitable for solving this problem:

const navigationRoutes: Routes = [
  { path: '',   redirectTo: '/select-fund', pathMatch: 'full' },
  { path: 'translate',   component: TranslateComponent, pathMatch: 'full' },
  { path: 'select-fund', loadChildren: () => import("your path to module").then(m => m.FeatureModule), pathMatch: 'full' },
  { path: '**', redirectTo: '/not-found', pathMatch: 'full' },
]; // defining the routes constant

// configuring NgModule imports and exports
@NgModule({
  imports: [RouterModule.forRoot(navigationRoutes,  { enableTracing: false })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

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

Oh no! A catastrophic NG_BUILD error has occurred: The mark-compacts are not working effectively due to an allocation failure near the heap limit. The JavaScript

While working on my Angular application, I keep encountering a JavaScript out of memory issue as indicated below: @bb-cli/bb-ang] ERR! NG_BUILD FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory I&apo ...

Refreshing the Angular directive following a change in the scope variable

Just getting started with Angular and I've encountered a small issue. Within my template for SirroccoListing, I have the following code. Sirrocco is a directive: <h3>All Sirroccos</h3> <div sirrocco ng-repeat="sirrocco in sirroccos" ...

What is the best way to apply an "active" class to the images that are displayed depending on the object's properties?

Below is a link to the JSON file I am working with - The JSON file consists of 5 main categories of runes, with each category containing 4 slots. Each slot has 3 runes, except for the first slot which has 4 runes. The code snippet below loops through the ...

Customize material-ui themes using useStyles / jss

Is it possible to customize the Material-UI theme using styles without relying on !important? const customTheme = createMuiTheme({ overrides: { MuiInputBase: { input: { background: '#dd7711', padding: 10, }, ...

Utilizing event binding with ngForTemplate in Angular 2

Imagine having a straightforward list rendering component: import {Input, Component } from 'angular2/core' @Component({ selector: 'my-list', template: ` <div *ngFor='#item of items' (click)='onItemClicked(i ...

What is the best way to create a type guard for a path containing a dynamic field

In certain scenarios, my field can potentially contain both a schema and an object where this schema is defined by key. How can a guard effectively tackle this issue? Below is an example of the code: import * as z from 'zod'; import type { ZodTy ...

When setupFilesAfterEnv is added, mock functions may not function properly in .test files

Upon including setupFilesAfterEnv in the jest.config.js like this: module.exports = { preset: 'ts-jest', testEnvironment: 'node', setupFilesAfterEnv: ["./test/setupAfterEnv.ts"] } The mock functions seem to sto ...

Is it possible to Use Vuejs 2 to Update MathJax dynamically?

Just figured out how to resolve this issue. Simply bind the data using v-html <div id="app"> <h1 v-html="equation"></h1> <button @click='change'>Change</button> </div> var vm ...

Establishing a standard value for a class that can be injected

Here is my desired approach: @Injectable() export class MyInjectableClass { constructor(timeout: number = 0) { } } The goal is to have the timeout set to 0 when it's injected, but allow the calling code to specify a different value when constr ...

Challenge in WordPress Development

As a beginner in website building, I am looking to customize the background of my pages with a solid color. The current SKT Full Width theme I am using has an opaque background which is causing the text on my slider to blend in and not look appealing. All ...

Implementing Github Oauth2 in a Rails server independent from a chrome extension

Looking to implement Github Oauth2 from my chrome extension, but rather than using chrome.identity.launchWebAuthFlow I want to handle it through my server. This way, I can avoid exposing my client ID and Client Secret in the javascript of the extension. My ...

Utilizing PHP Variables in JavaScript: A Comprehensive Guide

Is there a way to work around the inability to directly use PHP variables in javascript code? I need to incorporate these parameters into my javascript: username: '<?php echo $user_id;?>.example.co.uk', password: 'example', Inst ...

React is unable to identify the prop `controlID` when used on a DOM element in React-Bootstrap Forms

While constructing a form with React components sourced from react-bootstrap, and taking guidance directly from an example provided in its documentation: <Form.Group controlId="formBasicEmail"> <Form.Label>Email address</Form.Label> ...

Issue with starting @mauron85/cordova-plugin-background-geolocation on Ionic 5 and Angular 9 platform

I'm facing a challenge with integrating the background geolocation plugin into my app. Here is the documentation link for reference: https://ionicframework.com/docs/native/background-geolocation Here's the snippet of my code that initiates the p ...

Is there a Joomla extension available that can display or conceal content upon clicking?

Looking to enhance my Joomla site by installing a plugin that allows me to toggle the visibility of content with a click, similar to how FAQ sections work on many websites. Question 1 (click here for the answer) { Details for question 1 go here } Questi ...

Create a dynamic HTML page using JavaScript

When I click on the following links: How can I create a new page using JavaScript? Create and dynamically append elements I'm looking to dynamically add HTML elements with JavaScript within a div, but I don't want my code to become overly comp ...

Guide to converting a string into an undefined type

I've been working on parsing a csv file: let lines = csvData.split(/\r\n|\n/); let headers = lines[0].split(','); for (let i = 1; i < lines.length; i++) { let values = lines[i].split(','); ...

Ensuring that two operators are not consecutively placed in a Javascript calculator-validation guide

After creating a basic calculator using HTML, CSS, and JavaScript, I encountered an issue. When validating user input, the calculator currently accepts multiple operators in a row. To address this, I attempted to prevent consecutive operators by checking ...

Transforming sound data into a file format for submission to the backend system (without the need to store it on the

UPDATE: I found a few minor errors in this post, which have been fixed and resolved some of the issues. The other half of the problem is addressed in the accepted answer. ... I am currently capturing microphone audio on the client side (using Nuxt/Vue) a ...

Customizing CSS to differentiate the color of active card headers in a Bootstrap accordion

I currently have a basic bootstrap accordion set up, as shown below. My goal is to style the .card-header element of only the expanded .card section without impacting the other .card-header elements. Is there a way to specifically target the expanded ite ...