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

Jason Seah picture Jason Seah · Mar 28, 2016 · Viewed 132.6k times · Source

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?

Answer

Shaishab Roy picture Shaishab Roy · Mar 28, 2016

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