Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 routes in imported module override current

Here's the plunker: https://plnkr.co/edit/WIFNVIEVqls4gXk21Muj

There're 2 modules both have routes defined. Module 2 imports module 1 in order to use a component from it. You can never navigate to Module 2. Module 1 loads instead.

Module 1 routing:

const routes: Routes = [
  { path: '', component: Module1Component }
];

Module 2 routing:

const routes: Routes = [
  { path: '', component: Module2Component }
];

App routing:

const routes: Routes = [
  { path: 'module1', loadChildren: 'app/module1/module1.module#Module1Module' },
  { path: 'module2', loadChildren: 'app/module2/module2.module#Module2Module' }
];

Thank you.

like image 319
rook Avatar asked Feb 09 '17 03:02

rook


1 Answers

Two issues to get this working. First, there is a bug with the router that takes in account the order of your imported modules. For more details on the error, see this bug report: https://github.com/angular/angular/issues/12648

So to get around the bug, you need to change the order of your imports in module2.module.ts so that your module2 routing file is imported before you import module1.

@NgModule({
    imports: [
        routing, // this order is important
        Module1Module
    ],
    declarations: [
        Module2Component
    ]
})

Second, instead of exporting your routing module as a const using ModuleWithProviders export it as a class. aka change the module2 routing file (module2.routing.ts) to export a class like so (you'll need to import NgModule):

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

This should fix it for you. Here's a working plunker: https://plnkr.co/edit/5impstull9EBCUxlw26k

like image 76
eddierunner Avatar answered Oct 01 '22 21:10

eddierunner