Angular 2 dynamically changes the default route

I need to allow users of my application to change the default route whenever they want: I have a settings page where they can select the β€œpage” that they want to show when they first log in.

For example, now they are redirected to the Day when they log in, but they want to be able to change this and redirect to the week or month when they log in if they want.

{ path: 'planification', component: PlanificationComponent, children: [ { path: '', redirectTo: 'Day', pathMatch: 'full' }, { path: 'day', component: DayComponent }, { path: 'week', component: WeekComponent }, { path: 'month', component: MonthComponent }] } 

How can i do this?

@ angular / core: 2.4.7

@ angular / router: 3.4.7

Thank you for your help!

+5
source share
1 answer

In fact, you can use security devices to redirect to the correct URL before navigating:

 { path: '', canActivate: [UserSettingsGuard], redirectTo: 'Day', pathMatch: 'full' } 

And you can look like this:

 @Injectable() export class UserSettingsGuard implements CanActivate { constructor(private router: Router) { } canActivate() : boolean { var user = ...; if(user.defaultPage) { this.router.navigate([user.defaultPage]); } else { return true; } } } 

That way, you can switch to the new URL if the user with the overridden page exists or uses the default stream.

+5
source

Source: https://habr.com/ru/post/1264348/


All Articles