angularangular2-routingangular2-modules

Angular2 Routing: import submodule with routing + making it prefixed


I have a main module and some submodules. And I want to specify some not trivial routing between them.

I'd prefer defining the routes of a submodule within the submodule. E.g.:

@NgModule({
    imports: [
        /*...*/
        RouterModule.forChild([
            { path: 'country', redirectTo: 'country/list' },
            { path: 'country/list', component: CountryListComponent },
            { path: 'country/create', component: CountryCreateComponent },
            /*...*/
        ])
    ],
    declarations: [/*...*/],
    exports: [
        RouterModule,
    ],
})
export class CountryModule {}

I want to import this module with its own internal routing, but I want to make its whole routing prefixed.

const appRoutes = [
    { path: '', component: HomeComponent },
    /*... (basic routes)*/
];

@NgModule({
    imports: [
        /*...*/
        RouterModule.forRoot(appRoutes),
        CountryModule, // <- how to make its routing prefixed??
    ],
    declarations: [
        /*...*/
        AppComponent,
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule {}

This settings creates the following routes: /country, /country/list, etc., but I want to make them prefixed like this:

There are other modules that I want to access via another routing, e.g. a CityModule under /otherstuff/city/create and /otherstuff/city/list`.

My questions:

  1. Is it possible to import a module with its own routing and make its routes prefixed?
  2. Furthermore: Is there a way to make links between 2 submodules agnostically of their final (prefixed) routes?

UPDATE

The accepted answer is the best way to do it: create the routes in the module, register them externally. Thus you can modify the routes, e.g. prefix them (this is what I wanted), you can define guards, override or filter them, etc.


Solution

  • in your appRoutes add child route like

    const appRoutes = [
        { path: '', component: HomeComponent },
        {
        path: 'settings',
        component: CountryComponent,
        canActivate: [AuthGuard],
        children: COUNTRY_ROUTES
      },
    ];
    

    Create a separate routes file

    export const COUNTRY_ROUTES:Routes = [
      { path: 'country', redirectTo: 'country/list' },
      { path: 'country/list', component: CountryListComponent },
      { path: 'country/create', component: CountryCreateComponent },
    
    ];
    

    In CountryComponent.html

    <router-outlet></router-outlet>