Jason Seah Jason Seah - 1 year ago 145
Javascript Question

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

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 :

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/' it work and it return me an empty page how to you handle this kind of case happen ?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download