Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 submodule's forChild() routes overwrite root routes

I've faced with issue of overwriting root routes, when import child routes using loadChildren() call.

App routes declared as:

const routes: Routes = [
  { path: '', redirectTo: 'own', pathMatch: 'full' },
  { path: 'own', component: OwnComponent },
  { path: 'nested', loadChildren: () => NestedModule},
];
export const routing = RouterModule.forRoot(routes);

Nested submodule's routes:

const routes: Routes = [
  { path: 'page1', component: NestedPage1Component },
  { path: 'page2', component: NestedPage2Component },
  { path: '', redirectTo: 'page1', pathMatch: 'full' },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class Module1RoutingModule {}

I can get /own, /nested/page1, /nested/page2, but when I try to get root / - I'm getting redirect to /page1. Why does that happen, as it's declared in child module with RouterModule.forChild, how does it redirects not to /own ?

I've created simple plunk for repro - https://plnkr.co/edit/8FE7C5JyiqjRZZvCCxXB?p=preview

Does somebody experienced that behavior?

like image 367
ykravv Avatar asked Feb 05 '23 15:02

ykravv


1 Answers

Here is your forked and modified plunker: https://plnkr.co/edit/XilkY55WXle2hFF0Pelx?p=preview

Do not import that lazy-load module and change the root routes like this:

//import { Module1Module } from "./module1/module1.module"; // do NOT import it !

export const routes: Routes = [
  { path: '', redirectTo: 'own', pathMatch: 'full' },
  { path: 'own', component: OwnComponent },
  { path: 'module1', loadChildren: 'src/module1/module1.module#Module1Module' },
];

And the nested routes:

const routes: Routes = [
  //{ path: 'page1', component: Module1Page1Component },
  //{ path: 'page2', component: Module1Page2Component },
  //{ path: '', redirectTo: 'page1', pathMatch: 'full' },

  // do the routes like this..
  {
    path: '',
    component: Module1Component,
    children: [
      { path: '', redirectTo: 'page1', pathMatch: 'full' },
      { path: 'page1', component: Module1Page1Component },
      { path: 'page2', component: Module1Page2Component }
    ]
  },
];
like image 165
slaesh Avatar answered Feb 21 '23 08:02

slaesh