Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 dynamically change default route

I need to allow the users of my application to change the default route when they want: I have a parameter page where they can select the "page" they want to show first when log on.

For example for now, they are redirected to Day when they log on, but they want to be able to change that and to be redirected on week or month when they log on 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 that?

@angular/core: 2.4.7

@angular/router: 3.4.7

Thanks for your help!

like image 897
Sa Hagin Avatar asked Feb 17 '17 14:02

Sa Hagin


People also ask

What is dynamic routing in Angular?

Dynamic Routing means, that the route configuration of a module can vary at each load depending on the logic you define for the loading. The main trick is to use the ROUTES InjectionToken which is a low-level API for the router configuration.

What is navigateByUrl in Angular?

navigateByUrl is similar to Router. navigate , except that a string is passed in instead of URL segments. The navigation should be absolute and start with a / . Here's a basic example using the Router.navigateByUrl method: goPlaces() { this. router.


1 Answers

Actually you can use guards for this to redirect to correct url before navigation happens:

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

And you guard can looks 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;
    }
  }
}

So you can switch to new url when user with overriden page exists or use default flow instead.

like image 109
VadimB Avatar answered Sep 24 '22 14:09

VadimB