nobalG
nobalG

Reputation: 4630

Conditional routing not working in Angular Application

In my dev build in my angular project, In the child module's routing file I am doing something like below,

const routes = window.innerWidth > 768 ? desktopRoutes: mobileRoutes;

Then I am passing these routes to RouterModule.forChild(routes)

The dev build works like a charm, however, when I create a prod build and deploy it, this thing fails to work and only loads the mobileRoutes, Irrespective of the screen resolution.

Any suggestions or alternatives I should look into are welcome

Note: that desktop route components extend Mobile components, just adding the info if that helps!

Upvotes: 3

Views: 622

Answers (1)

georgeos
georgeos

Reputation: 2511

It's because in prod build, AOT (Ahead of time compilation) is used, pre-compiling your routes. So, your routes return the false value: mobileRoutes.

There are some workarounds

  1. Using router: resetConfig(config) You should pass as parameter the new configuration, as described in resetConfig documentation, changing only the required routes.

  2. Using guards with CanActivate


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if( window.innerWidth > 768 ){
    return true; // return desktopRoute
  }

  this.router.navigate(['main/']);  // mobileRoute
  return false;
}

Upvotes: 6

Related Questions