如何在Angular2中添加ngModule路由作为另一个ngModule的子路由?

时间:2016-08-19 06:13:33

标签: angular

我正在关注此tutorial以获得我的应用程序的体系结构。

要提供更多信息,请将A视为appModule,B是另一个主要模块。现在我想在B的NgModule内加载其他模块(<router-outlet>,其中有许多其他路由)。

有什么更好的方法来做到这一点?

This is what I want to achieve

这是我到目前为止所做的事情

-mainBoard (Folder next to app.Module)
    --mainBoard Routes
    --mainBoard Component
    --mainHeader Component
    --mainFooter Component
    --mainSidenav Component

    -Users  (Folder inside mainBoard)
    --User Module
    --User Routes
    --UserList Component
    --UserDetail Component
    --UserSetting Component

    -Departments (Folder inside mainBoard)
    --Department Module
    --Department Routes
    --DepartmentList Component
    --DepartmentDetail Component

-Auth (Folder next to mainBoard folder)
    --Auth Module
    --Auth Component
    --Auth Routes
    -Sign-in (Folder)
    --Sign-in Component
    -Sign-up (Folder)
    --Sign-up Component

-App Module

我有2个主要模块,mainBoard和Auth。 MainBoard有一个标题,sidenav,footer,在中心我想使用<router-outlet>加载用户和部门。

我想加载localhost/app/users加载用户列表,localhost/app/department加载部门列表。

我的main-board.module和users.module看起来像这样

// main-board.module.ts
import {MainBoardRouting} from './main-board.routes';

import {UsersModule} from './users/users.module';
import {DepartmentsModule} from './departments/departments.module';

@NgModule({
    imports :[
        MainBoardRouting,
        UsersModule,
        DepartmentsModule
    ],
    declarations : [
        MainBoardComponent,
        MainHeaderComponent,
        MainFooterComponent,
        MainSidenavComponent
    ],
    providers: []
})
export class MainBoardModule{}

// Users.module.ts

import {NgModule} from '@angular/core';

import {usersRouting} from './users.routes';
import {UserListComponent} from './user-list';
import {UserDetailComponent} from './user-detail';

@NgModule({
    imports :[
        usersRouting
    ],
    declarations : [
        UserListComponent,
        UserDetailComponent
    ],
    providers: []
})
export class UsersModule{}

// main-board.routes

import { RouterModule,Routes } from '@angular/router';

import {  MainBoardComponent  } from './main-board.component';

const MainBoardRoutes: Routes = [{
    path: 'app',
    component: MainBoardComponent
}];
export const MainBoardRouting = RouterModule.forChild(MainBoardRoutes);

//用户路由

import { Routes, RouterModule } from '@angular/router';

import { UserListComponent }    from './user-list';
import { UserDetailComponent }  from './user-detail';

export const usersRoutes: Routes = [
  {path: '', redirectTo: 'app/users', pathMatch:'full'},
  { path: 'users',  component: UserListComponent },
  { path: 'user/:id', component: UserDetailComponent }
];

export const usersRouting = RouterModule.forChild(usersRoutes);

我的方法是否正确让孩子NgModule拥有自己的路线,或者我是否必须将它们更改为简单组件并拥有main-board模块路线中的所有路线?

8 个答案:

答案 0 :(得分:1)

您的方法是正确的。在这种方法中,只需将 childmodule 导入 parentmodule 即可。 Childmodule 将负责它自己的路由。类似地,如果您有嵌套模块,则只需要在父路由中导入模块,而不是在一个地方声明许多路由。

答案 1 :(得分:1)

你的方法是对的。您希望将路由拆分为自己的子模块。从技术上讲,你可以将路线移动到合并的任何模块,但从长远来看,这可能是一个坏主意。

带有结果路线的Plunker https://plnkr.co/edit/Y9ReEwnBZNId48xX1CDR?p=preview

@Component({
  selector: 'users',
  template: `
    <div>
      <h2>Users</h2>
      <ul><li *ngFor="let user of users">{{user}}</li></ul>
    </div>
  `,
})
export class Users {
  users = ["John", "Joe"];
}

const usersRoutes = [
  {path: 'users', component: Users}
];
const UsersRoutes = RouterModule.forChild(usersRoutes);


@NgModule({
  imports: [ CommonModule, UsersRoutes ],
  declarations: [ Users ],
  exports: [ Users ]
})
export class UsersModule {}

答案 2 :(得分:1)

如前所述,但我想有点清楚。 使用子模块划分应用程序功能是非常好的,随着应用程序的增长,它们允许保持简单的代码结构。

管理此过程的最佳方法是拥有如下文件夹结构:

src
   - featureA
     - featureA.routes.ts
     - fefatureA.module.ts
     - component1
       - component1.ts
       - [...]
     - component2
       - component2.ts
       - [...]
     - [...]

   - featureB
     - featureB.routes.ts
     - fefatureB.module.ts
     - component1
       - component1.ts
       - [...]
     - component2
       - component2.ts
       - [...]
     - [...]

   - [...]

   - app-routing.module.ts
   - app.module.ts

在每个功能的模块中,您声明此特定模块的路由: file feature.routes.ts:

const routerConfig: Routes = [
    {
        path: '',
        component: Component1
    },
    {
        path: 'other',
        component: Component2
    }
]

他们会在您的功能模块中导入此路线 file feature.module.ts:

    import { routerConfig } from "./feature.routes";
        @NgModule({
          imports: [ 
            RouterModule.forChild(routerConfig),
          ],
        })
export class FeatureModule{}

最后要做的是导入路由模块中的所有内容,延迟加载非常适合于典型应用程序的性能。

file app-routing.module.ts:

import { FeatureAModule } from './featureA/featureA.module';
import { FeatureBModule } from './featureB/featureB.module';
    @NgModule({
      imports: [
        RouterModule.forRoot([
          { path: '', loadChildren: ()=> require("./featureA/featureA.module")["FeatureAModule"]},
{ path: 'feature-b', loadChildren: ()=> require("./featureB/featureB.module")["FeatureBModule"]},
        ],  
        { preloadingStrategy: PreloadAllModules}) //Define the loading strategy
      ],
    })
    export class AppRoutingModule {}

最终将路由模块导入您的app模块 文件app.module.ts:

import { AppRoutingModule } from './app-routing.module';

@NgModule({
  imports: [
    AppRoutingModule,
  ],
})
export class AppModule {}

答案 3 :(得分:0)

您需要在路由定义中使用loadChildren属性,而不是路由器中的子节点,然后指向子模块(作为由“#”分隔的字符串,或作为返回模块的函数)< / p>

答案 4 :(得分:0)

你的方法是正确的你应该将你的特定路由划分为模块,就像用户模块相关的路由进入用户模块一样,随着应用程序的大小增长,它将非常有用,我认为你应该尝试这些修改。

//主板路由文件

  import { RouterModule,Routes } from '@angular/router';

 import {  MainBoardComponent  } from './main-board.component';

  const MainBoardRoutes: Routes = [{
       path: 'app',
       component: MainBoardComponent
  }];
 export const MainBoardRouting = 
 RouterModule.forRoot(MainBoardRoutes); // use for root instead of for child 

答案 5 :(得分:0)

您需要的是loadChildren

child.module.ts

const childRoutes: Routes = [
    {
        path: '',
        component: ChildComponentA
    },
    {
        path: 'other',
        component: ChildComponentB
    }
]

@NgModule({
    imports: [
        RouterModule.forChild(childRoutes)
    ]
})
class MyChildModule {}

app.module.ts

const appRoutes: Routes = [
    {
        path: 'children',
        // If using a function that returns the Module,
        // it will be "eager-loaded"
        loadChildren: () => MyChildModule
        // When using a string, it will be lazy-loaded
        // loadChildren: './path/to/child.module#MyChildModule'
    }
]

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ]
})
class AppModule {
}

答案 6 :(得分:0)

下面我给了app.module和功能模块的示例路由模块。

app-routing模块路由文件包含主路由和功能模块路由文件,包含子根的生根。希望这有助于产生的特征是/ feature / books

app-routing.module.ts //在app.module.ts中导入此内容

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';

export const routes: Routes = [
  { path: 'feature', loadChildren: 'app/feature/feature.module#FeatureModule'},
  { path: '', redirectTo: 'feature', pathMatch: 'full' },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ]
})

export class AppRoutingModule {
}

feature-routing.module.ts //在feature.module.ts中导入它

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';

// ---- components imported----
import { BooksComponent } from './books/books.component';
import { FeatureComponent } from './feature.component';

const featureRoutes: Routes = [

  {
    path: '',
    component: FeatureComponent,
    children: [
      {path: '', redirectTo: 'books', pathMatch: 'full'},
      {path: 'books', component: BooksComponent},
      {path: '**', redirectTo: 'books', pathMatch: 'full'},
    ]
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(featureRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class FeatureRoutingModule {
}

答案 7 :(得分:0)

我在最近的项目中做到了这一点。这是样本

<强> app.routing.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

@NgModule({
imports: [
    RouterModule.forRoot([
        { path: '', loadChildren: '../home/home.module#HomeModule' },
        { path: 'settings', loadChildren: '../settings/settings.module#SettingsModule' },
        { path: 'home', redirectTo: '', pathMatch: 'full' }
    ])
],
exports: [
    RouterModule
]
})
export class AppRoutingModule {  
}

<强> home.module.ts

//all necessary imports

@NgModule({
imports: [
    CommonModule,
    TranslateModule,
    FormsModule,
    RouterModule.forChild([
        {
            path: '', component: HomeComponent, canActivate: [SecureGuard]
        }
    ]),
    ViewCountPipeModule
],
declarations: [
    HomeComponent
],
providers: [
    SecureGuard,
    CommonService
]
})
export class HomeModule {
}

<强> settings.module.ts

//all the necessary imports

@NgModule({
imports: [
    CommonModule,
    TranslateModule,
    FormsModule,
    RouterModule.forChild([
        {
            path: '', component: RouteHolderComponent,
            children: [
                { path: '', redirectTo: 'settings', pathMatch: 'full' },
                { path: 'settings', component: SettingsComponent },
                { path: 'profile', loadChildren: '../profile-settings/profile-settings.module#ProfileSettingsModule' },
                { path: 'account', loadChildren: '../account-settings/account-settings.module#AccountSettingsModule' }
            ], canActivate: [SecureGuard]
        }
    ]),
    RouteHolderModule
],
declarations: [
    SettingsComponent
],
providers: [
    SecureGuard, SettingsService
]
})
export class SettingsModule {
}

RouteHolderModule导出RouteHolderComponent,其中只有<router-outlet></router-outlet>个标记。