Angular 2 How to redirect to 404 or other path if the path does not exist

JavascriptAngularAngular2 Routing

Javascript Problem Overview


I was trying to redirect 404 / other path if the path does not exist in angular 2

I tried research there is some method for angular 1 but not angular 2.

Here is my code :

@RouteConfig([
{
    path: '/news',
    name: 'HackerList',
    component: HackerListComponent,
    useAsDefault: true
},
{
    path: '/news/page/:page',
    name: 'TopStoriesPage',
    component: HackerListComponent
},
{
    path: '/comments/:id',
    name: 'CommentPage',
    component: HackerCommentComponent
}
])

So example if I redirect to /news/page/ then it works and it return me an empty page how do you handle this kind of case happen?

Javascript Solutions


Solution 1 - Javascript

For version v2.2.2 and newer

In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404' instead of path: '/404':

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

For versions older than v2.2.2

you can use {path: '/*path', redirectTo: ['redirectPathName']}:

{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},

{path: '/*path', redirectTo: ['NotFound']}

if no path matches then redirect to NotFound path

Solution 2 - Javascript

As Angular moved on with the release, I faced this same issue. As per version 2.1.0 the Route interface looks like:

export interface Route {
    path?: string;
    pathMatch?: string;
    component?: Type<any>;
    redirectTo?: string;
    outlet?: string;
    canActivate?: any[];
    canActivateChild?: any[];
    canDeactivate?: any[];
    canLoad?: any[];
    data?: Data;
    resolve?: ResolveData;
    children?: Route[];
    loadChildren?: LoadChildren;
} 

So my solutions was the following:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '404', component: NotFoundComponent },
    { path: '**', redirectTo: '404' }
];

Solution 3 - Javascript

My preferred option on 2.0.0 and up is to create a 404 route and also allow a ** route path to resolve to the same component. This allows you to log and display more information about the invalid route rather than a plain redirect which can act to hide the error.

Simple 404 example:

{ path '/', component: HomeComponent },
// All your other routes should come first    
{ path: '404', component: NotFoundComponent },
{ path: '**', component: NotFoundComponent }

To display the incorrect route information add in import to router within NotFoundComponent:

import { Router } from '@angular/router';

Add it to the constructior of NotFoundComponent:

constructor(public router: Router) { }

Then you're ready to reference it from your HTML template e.g.

The page <span style="font-style: italic">{{router.url}}</span> was not found.

Solution 4 - Javascript

As shaishab roy says, in the cheat sheet you can find the answer.

But in his answer, the given response was :

> {path: '/home/...', name: 'Home', component: HomeComponent} > {path: '/', redirectTo: ['Home']}, > {path: '/user/...', name: 'User', component: UserComponent}, > {path: '/404', name: 'NotFound', component: NotFoundComponent}, >
> {path: '/*path', redirectTo: ['NotFound']}

For some reasons, it doesn't works on my side, so I tried instead :

{path: '/**', redirectTo: ['NotFound']}

and it works. Be careful and don't forget that you need to put it at the end, or else you will often have the 404 error page ;).

Solution 5 - Javascript

make sure ,use this 404 route wrote on the bottom of the code.

syntax will be like

{
    path: 'page-not-found', 
    component: PagenotfoundComponent
},
{
    path: '**', 
    redirectTo: '/page-not-found'
},

Thank you

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason SeahView Question on Stackoverflow
Solution 1 - JavascriptShaishab RoyView Answer on Stackoverflow
Solution 2 - JavascriptnuvioView Answer on Stackoverflow
Solution 3 - JavascriptrobnordonView Answer on Stackoverflow
Solution 4 - JavascriptWetteren RémiView Answer on Stackoverflow
Solution 5 - JavascriptHarikrishnan kView Answer on Stackoverflow