Sumama Waheed
Sumama Waheed

Reputation: 3609

Angular 2 importing another "sibling" module injects the wrong Component

So I have a module structure like this:

app 
----pages
---------dashboard
---------posts

Both dashboard and posts have their own routing.

Here is how the routing looks like:

Pages

const routes: Routes = [ 
  {
    path: '',
    component: Pages,
    children: [
      { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
      { path: 'dashboard', loadChildren: './dashboard#DashboardModule' } 
      { path: 'posts', loadChildren: './posts#PostsModule' }
    ]
  }
];

export const routing = RouterModule.forChild(routes);

Dashboard

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

export const routing = RouterModule.forChild(routes);

Posts

const routes: Routes = [
    {
        path: '',
        component: PostsComponent
    },
    ...
];
const routing = RouterModule.forChild(routes);

Everything works fine but when I try to import the PostsModule in the DashboardModule like this:

import { PostsModule } from '../posts';

@NgModule({
  imports: [
    routing, // Dashboard routes
    CommonModule, 
    ...
    PostsModule
  ]
})
export class DashboardModule { }

and load http://localhost:3000/#/dashboard, it shows the PostsComponent, instead of DashboardComponent just because I imported the "sibling" module

How can I fix this?

Upvotes: 2

Views: 836

Answers (1)

Michael Kucinski
Michael Kucinski

Reputation: 473

It seems to me that by loading the PostsModule into the DashboardModule, you are also importing the PostModule routes, which is incorrect. Because the order of the route definitions matters, the incorrect component is placed in the page

Without seeing the full modules, it's impossible to say your intended design. However, I'd separate any common services and components from the PostsModule into a PostsCommonModule:

@NgModule({
  declarations: [
     //common components
  ],
  providers; [
     //common service
  ]
})
export class PostsCommonModule { }

with can then be imported by both PostsModule and DashboardModule:

import { PostsCommonModule  } from './posts-common.module';

@NgModule({
  imports: [PostsCommonModule]
  //...
})
export class PostsModule { }

//dashboard.module

import { PostsCommonModule  } from '../posts/posts-common.module';

@NgModule({
  imports: [PostsCommonModule]
  //...
})
export class DashboardModule { }

Upvotes: 4

Related Questions