Teja
Teja

Reputation: 133

Angular 2 Different modules same routing

I am having two main routes, both loading same child module. Is there any possible way to have two routes with same name on the child module that loads two different components with respect to the main route.

Main Routes:

export const ROUTES: Routes = [{
    path: 'first',
    loadChildren: './features/common#CommonModule',
    canActivate: [AppAuthGuard]
}, {
    path: 'second',
    loadChildren: './features/common#CommonModule',
    canActivate: [AppAuthGuard]
}]

Now I'm expecting the common module to have routes something like this

export const routes = [{
        path: 'list', component: FirstListComponent, pathMatch: 'full' }
    },{
        path: 'list', component: SecondListComponent, pathMatch: 'full' }
    }]

So, I want something like

I know that the order of the routes matters. And the proposed way is not possible. Can anyone suggest any possible way to achieve this.

Upvotes: 3

Views: 980

Answers (2)

Hector
Hector

Reputation: 632

This works for me, and is more simple:

App routing

const routes: Routes = [
  {
    path: 'mobile',
    loadChildren: './view/mobile/mobile.module#MobileModule',
    canActivate: [MobileGuardService],
    data: {
      preload: false
    }
  },
  {
    path: 'desktop',
    loadChildren: './view/desktop/desktop.module#DesktopModule',
    canActivate: [DesktopGuardService],
    data: {
      preload: false
    }
  },
  {
    path: 'error',
    loadChildren: './view/error/error.module#ErrorModule',
    data: {
      preload: false
    }
  },
  {
    path: '',
    redirectTo: window.innerWidth < 768 ? `/mobile/etc/etc/etc` : `/desktop/etc/etc/etc`,
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: window.innerWidth < 768 ? `/mobile/etc/etc/etc` : `/desktop/etc/etc/etc`
  }
];

Mobile Guard

@Injectable({
  providedIn: 'root'
})
export class MobileGuardService implements CanActivate {

  constructor(
    private router: Router
  ) {
  }

  canActivate() {
    if (window.innerWidth >= 768) {
      this.router.navigate(['/']).then();
      return false;
    }
    return true;
  }

}

Desktop Guard

@Injectable({
  providedIn: 'root'
})
export class DesktopGuardService implements CanActivate {

  constructor(
    private router: Router
  ) {
  }

  canActivate() {
    if (window.innerWidth < 768) {
      this.router.navigate(['/m/']).then();
      return false;
    }
    return true;
  }

}

I do this way, becuase redirectTo make problems with guards :(

:)

Upvotes: 0

baj9032
baj9032

Reputation: 2592

Please set path like this

export const routes = [{
        path: 'first/list', component: FirstListComponent, pathMatch: 'full' }
    },{
        path: 'second/list', component: SecondListComponent, pathMatch: 'full' }
    }]

Upvotes: 1

Related Questions