简体   繁体   中英

Angular4 routing in module and submodule

I plan to create a structure as below (Routes in each routing.ts is to illustrate my idea)

app.module.ts
app.routing.ts  // Routes = [{ path: 'modA', module: moduleA }, { path: 'modB', module: moduleB }]
moduleA
  -- moduleA.module.ts
  -- moduleA.routing.ts  // Routes = [{ path: '', component: ListComponent }, { path: 'new', component: CreateComponent }]
  -- list.component.ts
  -- create.component.ts
moduleB
  -- moduleB.module.ts
  -- moduleB.routing.ts  // Routes = [{ path: 'a', component: AbcComponent }, { path: 'z', component: XyzComponent }]
  -- abc.component.ts
  -- xyz.component.ts

I want to group whatever in moduleA just in moduleA.module including its routing. Same as moduleB.

Then I wish to expose moduleA and moduleB to app.routing for me to register its module path. I expect:

/modA           show list component in moduleA
/modA/new       show create component in moduleA
/modB/a         show abc component in moduleB
/mobB/z         show xyz component in moduleB

How can I create above structure in Angular4? Please provide same workable code if possible.

I would suggest that since you are already breaking down the relative pieces into modules that you use lazy-loading which will have a performance increase in your app. By using lazing loading you will get the functionality you want right out of the box. Each module will define its routing relative to itself and the module will be served from the base route specified in the app.routing file.

app.routing.ts

RouterModule.forRoot([{
    path: 'modA',
    loadChildren: './moduleA/moduleA.module#ModuleA'
}, {
    path: 'modB',
    loadChildren: './moduleB/moduleB.module#ModuleB'
}]

moduleA.routing.ts

RouterModule.forChild([{
    path: '',
    component: ListComponent 
}, {
    path: 'new',
    component: CreateComponent
}]

moduleB.routing.ts

RouterModule.forChild([{
    path: 'a',
    component: AbcComponent 
}, {
    path: 'z',
    component: XyzComponent
}]

you need to use child routes. The /new will be a child of /modA like so:

Routes = [{ path: 'modA', component: AComponent,
              children: [
                { path: 'new', component: childComponent }
                 ] 
          },
          { path: 'modB', component: BComponent }
         ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM