17

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!

Giannis
  • 1,790
  • 1
  • 11
  • 29
Sa Hagin
  • 502
  • 1
  • 7
  • 18

3 Answers3

24

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.

VadimB
  • 5,533
  • 2
  • 34
  • 48
  • Wasn't able to get this solution to work with angular 2.4. I had to specify the path and component. – Android Noob Mar 15 '17 at 16:59
  • 3
    If you add `children: []`, it should work, and you won't have to specify a component. – Compeek May 16 '17 at 20:43
  • I have a case where the user will be allowed to route to a set of routes (will be displayed as tabs in the view) and the first of them should be routed to, by default. How to do this? – karthikaruna Aug 10 '17 at 10:21
  • 1
    EXCEPT, that bug causes canActivate to not be called on redirectTo routes in Angular 4...see [https://github.com/angular/angular/issues/18605](https://github.com/angular/angular/issues/18605) – user292701 Aug 28 '17 at 04:10
  • This was so... brilliant! – Nicolae Olariu Jan 16 '19 at 13:52
  • I got an error 'Invalid configuration of route '': redirectTo and canActivate cannot be used together.' to solve it, I just replaced the redirectTo with component:SomeAlternateComponent – EranKT Dec 07 '22 at 12:44
0

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".

Arthur Bouchard
  • 425
  • 6
  • 7
0

The accepted solution throws the following error in Angular 13 if the guard is not contained in "providers" of the AppRoutingModule/AppModule: Invalid configuration of route '': redirectTo and canActivate cannot be used together.

This solution worked for me with Angular 13: https://stackoverflow.com/a/52389428/8582981

Mario
  • 41
  • 1
  • 3
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 19 '23 at 08:08