Angular 2 How to redirect to 404 or other path if the path does not exist [duplicate]
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?
Solution 1:
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:
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' }
];