Jason Seah Jason Seah - 4 days ago 7
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 :

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

Answer

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

like:

{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

Comments