简体   繁体   中英

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!

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.

This is a compilation of Compeek and VadimB answers

You can use a guard to redirect to a route or another route, depending on the result of one of your custom methods.

In your routing:

{
    path: '',
    pathMatch: 'full',
    canActivate: [MyModuleRedirectGuard], // Will dynamically redirect to 'other-route1' or 'other-route2',
    children: []
    // redirectTo: 'other-route1' <= Will not dynamically redirect your user
},
{ path: 'other-route1', component: OtherOneComponent },
{ path: 'other-route2', component: OtherTwoComponent },

MyModuleRedirectGuard:

@Injectable()
export class MyModuleRedirectGuard implements CanActivate {
    constructor(
        private router: Router,
        private customService: CustomService
    ) {}

    canActivate(next: ActivatedRouteSnapshot): Promise<boolean | UrlTree> | boolean | UrlTree {
        return this.customService.canRedirectOtherRoute1().then((canRedirectOtherRoute1) => {
            if (canRedirectOtherRoute1) {
                return this.router.parseUrl('/my-module/other-route1');
            }

            return this.router.parseUrl('/my-module/other-route2');
        });
    }

children: [] is a hack to avoid " redirectTo and canActivate cannot be used together ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM