Angular 6 Fallback/Redirect if param is undefined

Viewed 517

I'd like to have routes set like this:

Base Route: /events/:date

A click event redirects to /events, then the routes file would have to fallback to /events/moment().format('YYYY-MM-DD') to render EventsComponent.

Inside EventsComponent you have an action to change date, which navigates according to the day you selected, in this case the routes file wouldn't need to fallback, since the :date is defined.

I just don't know how to apply it to my needs.
Thanks

1 Answers

If you just need to avoid navigation when the date parameter is not defined then you should have 2 routes and add a canActivate guard to the second:

{
   path: 'events',
   component: EventsComponent
},
{
   path: 'events/:date',
   component: EventsDetailComponent,
   canActivate: EventDefinedGuard
}

where EventDefinedGuard is a router guard that check for the param to be defined, otherwise redirects.

Related