Angular2 Routing: import submodule with routing + making it prefixed

前端 未结 2 949
我寻月下人不归
我寻月下人不归 2020-12-18 03:56

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 sub

相关标签:
2条回答
  • 2020-12-18 04:28

    Playing with this Routing stuff I just found a clean way I would like to share, to handle the routes of submodules with no headaches and love Angular even more. Taking the OP case as an example, I propose you to study the following code:

    Add a utility function to your CountryModule submodule, to load it dynamically from the Router and avoid a compiler warning about replacing the arrow function with a reference to an exported function:

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

    Now you can import that Entrypoint into your parent module where you want to place the routes:

    @NgModule({
      imports: [
        ...
        RouterModule.forRoot([
          { path: '', pathMatch: 'full', component: HomeComponent },
          { path: 'settings', loadChildren: CountryEntrypoint }
        ]),
      ],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    And there you go! You can now reach your submodule components with settings/country/list and settings/country/create.

    WARNING

    Be careful to not import the CountryModule into your parent module's @NgModule, because it will override the routes outside the settings path. Let the router do the job.

    Enjoy!

    0 讨论(0)
  • 2020-12-18 04:52

    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>
    
    0 讨论(0)
提交回复
热议问题