Multiple modules and routing in angular 5

后端 未结 2 1555
一向
一向 2020-12-25 14:16

can somebody tell me how correct to set up routing when using multiple modules in my project? I have app.module and courses.module with some components declared in. I want t

相关标签:
2条回答
  • 2020-12-25 15:04

    app.routing.module.ts

    const routes: Routes = [
      {
        path: '',
        children: [
          { path: 'courses', loadChildren: './components/courses/courses-routing.module#CoursesRoutingModule' }
        ]
      }
    ];
    

    courses.routing.module.ts

    const routes: Routes = [
      {
        path: '',
        children: [
          { path: 'list', component: CoursesListComponent}
        }
      }
    ];
    

    I would do it this way. Give it a try yourself and see how it goes.

    0 讨论(0)
  • 2020-12-25 15:18

    Edit 08/2019

    Adapted the lazy load module syntax to the newly, strong-typed syntax introduced in angular 8.

    Edit 02/2020:

    This construct is still valid for Angular 9.

    Solution

    Here is how I do it:

    app.module.ts

    import {ModuleRouting} from './app.routing';
    
    @NgModule({
        declarations: [
            AppComponent,
        ],
        imports: [
            ModuleRouting,
            SubmoduleModule         
        ]
        bootstrap: [AppComponent]
    })
    export class AppModule {
    }
    

    app.routing.ts

    import {Routes, RouterModule} from '@angular/router';
    import {ModuleWithProviders} from '@angular/core';
    
    const routes: Routes = [
        {path: 'submodule', loadChildren: () => import('app/submodule/submodule.module').then(m => m.SubmoduleModule)}
    ];
    
    export const ModuleRouting: ModuleWithProviders = RouterModule.forRoot(routes);
    

    submodule.module.ts

    import {NgModule} from '@angular/core';
    import {CommonModule} from '@angular/common';
    import {ModuleRouting} from './submodule.routing';
    
    @NgModule({
        imports: [
            CommonModule,
            ModuleRouting
        ],
        declarations: [
            //...
        ]
    })
    export class SubmoduleModule {
    }
    

    submodule.routing.ts

    import {RouterModule, Routes} from '@angular/router';
    import {ModuleWithProviders} from '@angular/core';
    
    const routes: Routes = [
        {
            path: '',
            component: SomeComponent,
        },
        {
            path: 'other',
            component: SomeOtherComponent,
        }
    ];
    
    export const ModuleRouting: ModuleWithProviders = RouterModule.forChild(routes);
    

    You can also generate the module and routing files using the angular cli and then adapt them: (cd to the directory where the files should be created before every command)

    ng g m module --routing
    ng g m submodule --routing
    
    0 讨论(0)
提交回复
热议问题