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

Matching the scope property in AngularJS directives

I am currently working on creating a custom directive that will perform regex validation on specific input fields. The goal is for the directive to determine which regex pattern to use based on an attribute provided in the input element. Here is an exampl ...

Is there a reliable method to verify the correctness of an HTML input?

I'm currently developing a quiz using <input type="text"> and <input type="number">. I've noticed that relying on numerous if / else statements in my code is proving to be highly inefficient due to the sheer amoun ...

Deleting an List Item from an Unordered List using Angular

Within my MVC controller, I have an unordered list with a button on each item that allows the user to remove it from the list. The issue I'm facing is that while the row is deleted from the database, it still remains visible on the screen. This is ho ...

The server has sent cookies headers, however, the browser did not store the cookies

I need assistance in understanding why browsers such as Chrome are not setting cookies, even though the Set-Cookie header is present in the Response Headers: Access-Control-Allow-Origin: * Connection: keep-alive Content-Length: 345 Content-Type: applicati ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

Utilizing Regular Expressions in Angular 4 by Referencing Patterns Stored in an Object

I'm facing an issue where my code is functional, but I keep encountering a Tslint error that's proving difficult to resolve. This particular configuration worked fine with Angular 1, but now I'm in the process of migrating the application to ...

Troubleshooting: Issue with Updating Prototype Ajax Function

I am currently utilizing Prototype within the pylons framework and attempting to execute an Ajax call. Below is the structure of my html: <form method="POST" action = "javascript:void(0)" onsubmit = "new Ajax.Updater('graph','/saffron_m ...

Steps to close a socket upon session expiration

I am currently working on a small express application that also incorporates a socket program. Everything works perfectly when a user successfully logs in - it creates the session and socket connection seamlessly. However, I encountered an issue where eve ...

Is there a way to show a 'Refresh' icon in HTML without the need to download an image through HTTP?

In my HTML/JavaScript app project, I am looking to incorporate a 'refresh' symbol without having to load an image through HTTP requests. Are there reliable methods that can achieve this across all major browsers? I came across the Unicode value: ...

Protractor functions perfectly on localhost, but encounters a Timeout error when used remotely - the asynchronous callback was not executed within the specified timeout period

Running protractor protractor.conf.js --baseUrl=http://localhost:4200/ executes successfully by filling data, validating elements, etc. However, when attempting to test the same website through a remote URL protractor protractor.conf.js --baseUrl=http://t ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

Unable to postpone the utilization of data in Vue until after retrieving the value from the database

I am facing an issue where I need to compare a string obtained from Firebase in document.check1 with specific strings (hardcoded in the function below) and display content accordingly. Currently, I know how to trigger this comparison on button click, but I ...

Sort attributes by the type of property

Is there a way to create a customized type by extracting specific properties from a generic type? class Test { value1!: Date value2!: number value3!: Date value4!: string } type FilterProperties<T, TFieldType> = //looking for a solution to se ...

Tips for exchanging JavaScript variables with PHP using AJAX

Hey there, I'm new to JavaScript and I've hit a roadblock with passing variables to PHP using Ajax. <script> $date = "123"; $.ajax({ url: './record.php', type: "POST", ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

Is there a way to retrieve JSON data using Vue and Axios?

I'm facing an issue trying to retrieve product data from a JSON file. Despite attempting different methods and searching for solutions online, I have not been able to find one that fits my specific scenario. As I am new to both Vue and axios, I apprec ...

The DOM fails to reflect changes in the data variable in VueJS

I am facing an issue while trying to update an array of arrays and display it as a reactive variable, however the DOM does not seem to reflect those changes. To achieve this, I have two components - a parent component and a child component: Parent Compon ...

Error message: When using Vue CLI in conjunction with Axios, a TypeError occurs stating that XX

I recently started working with Vue.js and wanted to set up a Vue CLI project with Axios for handling HTTP requests. I came across this helpful guide which provided a good starting point, especially since I plan on creating a large project that can be reus ...

Starting a tab just once

I have successfully created 4 static HTML pages that include: Home About Services Contact Each page contains a link that leads to another static page named myVideo.html, which plays a video about me in a new tab. The link is available on every page so ...

Exporting variables in node.js allows you to share data between different

Hi, I'm currently working with a file that looks like this: module.exports = { some variables that are being exported here, execute(message) { } } I want to export the message parameter to another file. I've attempted using var msg ...