'Equivalent of Angular 1 otherwise route in Angular 2
I'm using Angular 2 routing for my application and it works pretty well but I have no idea how to define the "otherwise" route. So a route that will be displayed if none if the current URL does not correspond to any "supported" route.
Here is an example of my current configuration:
@RouteConfig([
{ path: '/', name: 'Home', component: StoryComponent, useAsDefault: true },
{ path: '/story', name: 'Story', component: StoryComponent },
{ path: '/subscription', name: 'Subscription', component: SubscriptionComponent}
])
Solution 1:[1]
This hasn't currently been implemented in angular 2. The best current solution is to use a solution like @Gary showed.
{ path: '**', component: PageNotFoundComponent }
as shown in the angular guide routing section(https://angular.io/docs/ts/latest/guide/router.html).
Solution 2:[2]
There is no 'otherwise' route in angular 2 yet. But the same functionality can be achieved using wildcard parameter, like so:
@RouteConfig([
{ path: '/', redirectTo: ['Home'] },
{ path: '/home', name: 'Home', component: HomeComponent },
// all other routes and finally at the last add
{path: '/*path', component: NotFound}
This will only load the 'NotFound' component and the url will be same as what you navigate to. In case you want all not matching routes to redirect to a '404' url, you can do something like:
//at the end of the route definitions
{ path: '/404', name: '404', component: PageNotFoundComponent },
{ path: '/*path', redirectTo:['404'] }`
Solution 3:[3]
Try this instead of otherwise. It works for me, not sure but seems like work in progress.
@RouteConfig([
{ path: '/**', redirectTo: ['MycmpnameCmp'] },
...
}
])
Solution 4:[4]
This worked for me:
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
// all other routes
{ path: '**', redirectTo: '/home' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Solution 5:[5]
Try this
RouterModule.forRoot([
{ path: 'login', component: LoginComponent },
{ path: 'edit-event', component: EventComponent },
{ path: 'participants', component: ParticipantsComponent },
{ path: 'notification', component: NotificationComponent },
{ path: '', component: WelcomeComponent }, //default
{ path: '**', component: WelcomeComponent } //page not found route
], { useHash: true })
useHash parameter is for using hash url style https://angular.io/docs/ts/latest/guide/router.html#!#route-config
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David Wolf |
Solution 2 | Abu Romaïssae |
Solution 3 | Gary |
Solution 4 | Steve Brush |
Solution 5 | Varun Kumar |