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?
This question is related to
javascript
angular
angular2-routing
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.
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 ;).
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' }
];
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
Source: Stackoverflow.com