VFein
VFein

Reputation: 1061

Importing Module without routes

I have a situation where our main app lazily loads other modules:

//main NgModule
RouterModule.forRoot(
[
  {path:'profile', loadChildren:'path/to/profile.module#ProfileModule}, 
  {path:'classroom', loadChildren:'path/to/classroom.module#ClassroomModule},
  {path:'tests', loadChildren:'path/to/test.module#TestsModule}
])

Now the profile module has a few components in it that are necessary for the Classroom module.

//Profile NgModule
RouterModule.forChild(
[
  {path:'', component:ProfileComponent, 
])

//Classroom NgModule
imports: [
  ProfileModule,
  RouterModule.forChild(
  [
    {path:'', component:ClassroomComponent} //this requires a component in ProfileModule
  ])
]

This compiles nicely but when I try to navigate to '/classroom' all I get is the ProfileComponent

I suppose this is because the ProfileModules route configuration is being combined with the ClassroomModule route configuration. Is there a way I could prevent this from happening? I'd prefer not having to remove all of the shared components from ProfileModule and putting them into a new shared module if possible.

Upvotes: 30

Views: 8888

Answers (3)

chipro
chipro

Reputation: 31

I have encountered a similar issue. All I found is that if you put a module already combined with a RouterModule before the current module's routing module, it will just use the imported module's routing if any path matches the pattern. So make sure your routing module is imported at the very beginning, just after CommonModule maybe, it'll be safer.

Upvotes: 3

rogermushroom
rogermushroom

Reputation: 5586

The best way I found to do this was to create a Module which does all the declarations of the original module but without importing the routing.

<Module Name>WithoutRouting.ts

I then create anther module

<Module Name>.ts

Where I import the routing and the <Module Name>WithoutRouting.ts module.

Then when I want to use the module with routing, for example when lazy loaded I use <Module Name>.ts and if I want to import the Module directly I use <Module Name>WithoutRouting.ts.

Upvotes: 27

Michele Dibenedetto
Michele Dibenedetto

Reputation: 575

try to invert the position of the imports

 //Classroom NgModule
    imports: [
      RouterModule.forChild(
      [
        {path:'', component:ClassroomComponent} 
      ],
      ProfileModule
)

Upvotes: 1

Related Questions