Angular 2 fails to redirect to a 404 page if both the route parameter and address are not valid

Currently, while working on my application with Angular 4.1.1, I have a habit of declaring routing in every module I create.

For instance, in the file new-cars.routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { NewCarsComponent} from './new-cars.component';
import { NewCarsResolver } from './new-cars.resolver';    

@NgModule({
    imports: [
        RouterModule.forChild([
            {
                path: 'cars/:id',
                component: NewCarsComponent,
                resolve: {
                    card: NewCarsResolver
                }
            }
        ])
    ],
    exports: [RouterModule]
})

export class NewCarsRoutingModule { }

I also define routes in the app-routing.module.ts to handle incorrect routes:

export const routes: Routes = [
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true})],
  exports: [RouterModule]
})

export class AppRoutingModule {}

To properly manage misconfigured URLs, I ensure that addresses are formatted as follows:

http://foowebsite/#/sdf /*this address exists*/

However, if the URL is incorrectly inputted like below:

http://foowebsite/#/news/-5  /*There is no route param "-5". It should show a 404 error page instead of redirecting to home*/

http://foowebsite/sdf  /*This routing does not exist. Instead of redirecting to home, display a 404 error */

Various attempts were made such as:

export const routes: Routes = [
  { path: '404', component: PageNotFoundComponent },
  { path: '**', component: PageNotFoundComponent }
];

along with:

export const routes: Routes = [
  { path: '404', component: PageNotFoundComponent },
  { path: '**', redirectTo: '/404' }
];

Unfortunately, these configurations still redirect invalid URLs to the home page. Keep in mind that module routing handles module-specific routes and application routing directs to a 404 page.

In my app.module.ts file:

import { AppRoutingModule } from './app-routing.module';

@NgModule({
    imports: [
        ...
        AppRoutingModule        
    ],
    declarations: [
        AppComponent,
        PageNotFoundComponent
        ],
    bootstrap: [AppComponent]
})
export class AppModule { }

In the ASP.NET Core Web Application web.config file, the setup is as follows:

<system.webServer>
    <httpErrors>
      <remove statusCode="500" subStatusCode="-1" />
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" prefixLanguageFilePath="" path="/404" 
                                                responseMode="ExecuteURL" />
      <error statusCode="500" prefixLanguageFilePath="" path="/404" 
                                                responseMode="ExecuteURL" />
      <error statusCode="500" subStatusCode="100" path="/404" 
                                                responseMode="ExecuteURL" />
    </httpErrors>
</system.webServer>

Even deliberately returning a 404 error code doesn't trigger the error page:

[HttpGet("{name}")]
public async Task<IActionResult> Get(string name)
{
    return StatusCode(404);
}

Can someone provide guidance on how to correctly redirect to the 404 page?

Answer №1

Give this a shot:

{path: '404', component: PageNotFoundComponent },
{path: '**', redirectTo: '/404'}

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

Gather every hyperlink and input fields without utilizing jQuery

Is there a way to target all a and form elements without relying on jQuery? My end goal is to achieve the following functionality: document.querySelectorAll('a').forEach(element => { element.addEventListener('click', () => { ...

Having difficulties with JavaScript's if statements

I'm facing an issue with my JavaScript code that is meant to modify the value of a price variable and then display the updated price. The problem arises when I have multiple select options, as the price only reflects the ID of the last statement. Here ...

Managing a single Angular project with multiple apps that share common features: A guide

Imagine having multiple Angular 'apps' with similar features and functions, where one product needs to be customized for different clients with slightly varying needs. The challenge lies in developing within a single code base. Using feature mod ...

Running `ng start angularProject` or `npm install` will generate additional files in the project's

I'm encountering a major issue where every time I create a new project using 'ng start' or run 'npm install', extra files are being generated in the root folder like this. https://i.stack.imgur.com/BUphZ.png Here is my package.js ...

Identifying modifications within the @Input property in Angular 4

Can someone clarify how to detect changes in an @Input property within a component, rather than just when passed from its parent? I haven't found a clear answer to this yet. Thank you! ...

How to automatically select the first item in a populated dropdown list using Vue JS

My HTML select element is populated with options from a server, but when using v-model, it initially selects an empty option instead of the first one. I came across a solution on a post which suggests selecting the first option manually, but since the dat ...

Why does the CLI crash when attempting to retrieve all data from an Oracle Database with JQuery?

Trying to utilize JavaScript and Jquery for database search, a generic query.php file has been set up to pass in the database and query, returning an array. Strangely, when attempting to select all using *, the PHP server crashes with: https://i.stack.img ...

Adding HTML content using jQuery's document.ready feature

As a jQuery novice, I am attempting to incorporate a Facebook like button using the jQuery document.ready function. In my external Javascript file (loaded after the jQuery script), you will find the following code snippet: $(document).ready(function(){ ...

Cloning jQuery with varied PHP array value

So, I have the given PHP values: PHP: <?php $names = array("Mike","Sean","Steve"); ?> <script type="text/javascript"> var name_data = <?php echo json_encode($names); ?>; </script> <div class="container"> <div cl ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

When we typically scroll down the page, the next section should automatically bring us back to the top of the page

When we scroll down the page, the next section should automatically bring us back to the top of the page without having to use the mouse wheel. .bg1 { background-color: #C5876F; height: 1000px; } .bg2 { background-color: #7882BB; height: 1000px; } .bg3 ...

Enzyme's simulate() failing to produce expected results with onChange event

I am facing an issue with a component and its related tests: import React from 'react'; import PropTypes from 'prop-types'; function SubList (props) { var subways = ['', '1', '2', '3', & ...

The use of jQuery.parseJSON is ineffective for a specific string

Why isn't jQuery.parseJSON working on this specific string? ({"stat":"OK","code":400,"data":[{"title":"Development Convention","event_type":false,"dates_and_times":[{"date":"28\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"dat ...

Attempting to convert numerical data into a time format extracted from a database

Struggling with formatting time formats received from a database? Looking to convert two types of data from the database into a visually appealing format on your page? For example, database value 400 should be displayed as 04:00 and 1830 as 18:30. Here&apo ...

Transforming ajax code into node.js

After mastering ajax calls for client-server interaction, I am facing a challenge in converting my code to a server-side node compatible JS using http requests. Despite reading various tutorials, I am struggling to adapt them to fit with my current code st ...

Fix for sorting issue in Angular 4.4.x mat-table header

I am facing an issue with my mat-table sorting header. I have followed the examples and decorated the columns accordingly: <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef mat-sort-header> Id </mat-header-cell> & ...

What is the best way to shrink or enlarge individual sections of the accordion?

Exploring AngularJs Accordions I'm struggling to understand how to control accordions in AngularJS. I have a step-by-step module set up as an accordion and I want to collapse one part while expanding another based on completion. Here is the accordion ...

What is the best way to load a partial in Rails asynchronously with AJAX?

I am currently using the following code to load a partial when I reach the bottom of a div containing a table: $(document).ready(function () { $("#pastGigs").scroll(function () { if (isScrollBottom()) { $('#pastGig ...

Using two loops/arrays in JavaScript to generate a rating score

I want to create a simple rating component with the following appearance: ◼◼◼◻◻ (score: 3 out of 5) Here is my JSX code snippet: var score = 3; var range = 5; { [...Array(range)].map((e, i) => ( <div className="rating-item" ...

The MaterialUI Datagrid is throwing an error message for an Invalid Hook Call

Having a strange issue with my simple component. I've imported DataGrid from MaterialUI, defined variables for columns and rows, and rendered the DataGrid in a functional component. However, I'm getting an "invalid hook call" error. Most solution ...