Angular 5 - nested route from imported module

38 views
Skip to first unread message

Arnaud Deman

unread,
Feb 20, 2018, 10:06:19 AM2/20/18
to Angular and AngularJS discussion
Hi,

What is the correct way to define nested route from another module ?

I have 2 modules: one named NamespaceModule which import another one named CorpusModule. I would like to define routes like this: /namespace/admin-namespace/corpus/admin-corpus

I have tryed this way : 

Route defined in namespace-routing.module :

const routes: Routes = [
{ path: 'namespace/:name', component: NamespaceComponent,
},

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


Same principle in CorpusRoutingModule:

const routes: Routes = [
{
path: 'corpus/:name', component: CorpusComponent,
}
];
(...)
@NgModule({ (...)
export class CorpusRoutingModule {}


In NamespaceModule I import NamespaceRoutingModule and CorpusModule :
@NgModule({
imports: [
CommonModule,
FormsModule,
NamespaceRoutingModule,
CorpusModule,
(...)
})
export class NamespaceModule {
(...)
}


This is not working as I would like because the routes are flattened out:
/namespace/admin-namespace and /corpus/admin-corpus are valid but not /namespace/admin-namespace/corpus/admin-corpus

The only way I found is to define a child route in  NamespaceRoutingModule but I don't like this because I think this should be defined in the CorpusModule.

const routes: Routes = [
{ path: 'namespace/:name', component: NamespaceComponent,
children: [
{ path: 'corpus/:name', component: CorpusComponent }
]
},
];
 
Thanks for your help,
Regards,
Arnaud.

Arnaud Deman

unread,
Feb 23, 2018, 9:48:01 AM2/23/18
to Angular and AngularJS discussion
Hi,
I think I have found a way for doing this, if someone else want to do the same thing.

I export the routes array from the imported module 

export const routes: Routes = [
{
path: 'corpus/:name', component: CorpusComponent,
}
];

And I use it in the parent module to build its routes array. The nested route is defined in the parent without knowlege of the routes in the imported module :

import { routes as corpusRoutes } from '@corpus/corpus';
import { NamespaceExistsGuard } from './namespace-exists.guard';

const routes: Routes = [
{
path: 'namespace/:namespace', component: NamespaceComponent,
canActivate: [NamespaceExistsGuard],
children: [
...corpusRoutes
]
}
];

Regards,
Arnaud.
Reply all
Reply to author
Forward
0 new messages