Tips for effectively managing 404 errors in Angular 10 with modular routing

I'm facing challenges with handling 404 pages within an Angular 10 application that utilizes modular routing architecture.

Here is the structure of my code:

|> app
|-- app.module.ts
|-- app-routing.module.ts
|-- app.component{ts, spec.ts, scss, html}
|-> pages
|--- pages.module.ts
|--> home-page
|---- home-page.module.ts
|---- home-page-routing.module.ts
|---> home-page
|----- home-page.component{ts, spec.ts, scss, html}
|--> test-page
|---- test-page.module.ts
|---- test-page-routing.module.ts
|---> test-page
|----- test-page.component{ts, spec.ts, scss, html}

The global app-routing module has a 404 handler configured as seen below:

...
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },

  // If the following line is not commented out,
  // You are unable to navigate to either the 'Home' or 'Test' pages.
  // { path: '**', component: PageNotFoundComponent },
];

...

The issue I am encountering is that Angular resolves to the global 404 handler in ./app/app-routing.module.ts instead of the intended page route.

I have provided a sample StackBlitz showcasing this behavior (Note: The StackBlitz example is running Ng12, but our app is using Ng10 with similar behavior)

My objective is to implement a global 404 handler or redirection functionality while maintaining separate definitions for page routes within their respective module-routing files.

Is it possible to achieve this, and if so, how?

Answer №1

Upon reviewing your Stackblitz, it appears that the issue lies in the order of imports within the AppRoutingModule, with it being imported before the PagesModule.

To resolve this, ensure that you import the PagesModule first as its routes should take precedence.

  imports: [
    BrowserModule,
    RouterModule,
    FormsModule,
    PagesModule,
    AppRoutingModule,
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}

An alternative (and preferable) solution would be to implement lazy loading for the module:

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  {
    path: '',
    loadChildren: () =>
      import('./pages/pages.module').then((m) => m.PagesModule),
  },
  { path: '**', component: PageNotFoundComponent },
];

This approach eliminates the need to import the entire PagesModule into your AppModule.

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 best way to prevent a directory from being included in the Webpack bundle?

Issue: Despite configuring my Webpack settings in webpack.config.js to exclude files from the ./src/Portfolio directory, all files are being bundled by Webpack. Code Snippet: Webpack.config.js const path = require('path'); module.exports = { ...

Is randomly pairing 2 datapairs after slicing a JSON array easy or challenging?

There is a JSON file containing an unlimited number of users [{ "fname": "Hubert", "lname": "Maier", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bd ...

Efficient AJAX validation using PHP and JavaScript

I am currently working on a small website project that requires User registration functionality. One key aspect is ensuring that the system prevents users from registering with usernames that are already in use. Most modern websites employ AJAX to verify ...

Tips for dynamically adding an external SVG animation to your website:

When trying to insert an animated SVG using jQuery or plain JavaScript, they appear static in Chrome and Edge, but display correctly in Firefox: $(".loader").prepend("<svg><use xlink:href='/images/icons.svg#loading-ring'></use> ...

Issues with lazy loading in swiper.js when trying to display multiple images per slide

I recently tried using swiper.js and had success with the lazy loading demo. However, I encountered an issue where only one image per slide was showing up, despite wanting to display 4 images per slide. <div class="swiper-container"> <div cla ...

Is it possible for a chrome extension to allow only specific third-party cookies and storage to be

My Chrome extension inserts an iframe from foo.com into bar.com, creating a situation where bar.com now includes a foo.com iframe. However, I have observed that this iframe encounters difficulties when attempting to write to localStorage if the user has ...

Ensuring the image is properly sized to fit the screen and enabling the default zoom functionality

I am looking to achieve a specific behavior with an image, where it fits the viewport while maintaining its aspect ratio and allowing for zooming similar to how Chrome or Firefox handle local images. Here are the details of my project: The image I have is ...

Error: Attempting to access 'map' property of an undefined variable in NEXTJS

I've been struggling to retrieve an image from this API using getStaticProps, but for some reason I can't seem to make it work. In my code snippet, if I add a question mark like this, the console returns 'undefined'. What could be caus ...

Tips on utilizing a function that was generated within the constructor

I'm currently in the process of developing a function within the constructor, and it is essential that this function be placed inside the constructor. I am interested in implementing a button to trigger this function from an external source, but unfor ...

React text hover image functionality

Just diving into the world of React and attempting to create a cool image popup effect when you hover over text in my project. I could really use some guidance on how to make it function within React, as the logic seems a bit different from plain HTML. Any ...

Utilizing RxJS finalize in Angular to control the frequency of user clicks

Can someone provide guidance on using rxjs finalized in angular to prevent users from clicking the save button multiple times and sending multiple requests? When a button click triggers a call in our form, some users still tend to double-click, leading to ...

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...

Retain the previously selected option in a PHP combobox even when changing pages

Can someone please assist me with my PHP code? I am having trouble keeping my combobox unchanged after a page reload. It works fine until I change pages in my pagination. Can anyone help? THIS IS MY PHP. PHP ...

Passing a service into a promise in Angular 2 using TypeScript

Is there a way to pass a service into a promise? I am currently working on a promise that will only resolve once all the http requests are complete. However, I am facing an issue where this.jiraService is undefined. Is there a method to pass it to the co ...

Executing TipTap commands from a script tag in Vue 3: A step-by-step guide

One of the components I'm working with includes the following: <button @click="$refs.image.click(); editor.chain().focus().setImage({ src: state.image }).run()"></button> <input type="file" ref="image" sty ...

The conversion from a relative path to an absolute path in Node is producing unexpected results

Hello everyone, I'm facing a problem with the function sendDownload(), specifically with the objPathArray parameter that I am receiving in this format: [{"pathToFile":"./REPORTS/portfolio/onDemand/Portfolio_report_HP_17.08.2021.xlsx","file":"Portfolio ...

Is it possible to create a return using messageEmbed in Discord?

I have been working on creating a Discord bot that responds to the ! status command with the server status. I took inspiration from this existing bot. The only change I made was to ensure that the bot replies immediately to the ! status command without re ...

What is the method for altering the color of specific columns?

I am currently testing out my Amchart with this example. Check out the working demo on code pen My goal is to modify the color of the first four columns. While I am aware that colors can be changed by specifying them in the JSON file as a property calle ...

Navigating through this object with PUG and Express: a step-by-step guide

I am currently working on a basic blockchain project to practice my skills with nodejs. I have created a blockchain object that consists of a block class, and now I want to loop through this object using pug. app.get('/', function(request, respon ...

Switch between using a dropdownlist and textbox depending on the selection in another dropdownlist

In the process of developing an application, I have implemented a country dropdown list and a state dropdown list. Here's the scenario: when a user selects a country, the states for that country will populate in the state dropdown list. However, the ...