【问题标题】:What's the best way to organize Routes in angular2在angular2中组织路线的最佳方式是什么
【发布时间】:2016-09-24 13:47:20
【问题描述】:

我对 angular2 中的路线有疑问。今天我用的是和angular2官方教程一样的例子。 代码是这样的(file link):

// app.routing.ts
import { ModuleWithProviders }  from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { DashboardComponent }   from './dashboard.component';
import { HeroesComponent }      from './heroes.component';
import { HeroDetailComponent }  from './hero-detail.component';

const appRoutes: Routes = [
  {
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full'
  },
  {
    path: 'dashboard',
    component: DashboardComponent
  },
  {
    path: 'detail/:id',
    component: HeroDetailComponent
  },
  {
    path: 'heroes',
    component: HeroesComponent
  }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

我的问题是。如果我有多个 crud,我会得到一堆组件(例如实体/列表、实体/添加、实体/编辑、实体/显示)

那么,如何解决这个问题?在不创建混乱组件的情况下组织路线的最佳方法是什么?

【问题讨论】:

    标签: angular angular2-routing angular2-template angular2-directives


    【解决方案1】:

    跟随Routing & Navigation Guide。更具体地说,这些部分:

    创建功能模块(里程碑 #2):对于处理不同职责的每个组件,在应用程序的根文件夹中创建一个新文件夹,并将必要的组件、路由和服务放入其中。然后,定义一个模块将它们组合在一起。在您的情况下,创建一个名为 entity 的新功能模块并将必要的组件放入该模块中。功能模块示例(取自 Angular2 文档):

    import { NgModule }       from '@angular/core';
    import { CommonModule }   from '@angular/common';
    import { FormsModule }    from '@angular/forms';
    
    import { HeroListComponent }    from './hero-list.component';
    import { HeroDetailComponent }  from './hero-detail.component';
    
    import { HeroService } from './hero.service';
    
    @NgModule({
      imports: [
        CommonModule,
        FormsModule
      ],
      declarations: [
        HeroListComponent,
        HeroDetailComponent
      ],
      providers: [
        HeroService
      ]
    })
    export class HeroesModule {}
    

    制作子路由(里程碑#2):为每个功能模块定义一个路由文件,该文件定义了当前功能模块的必要路由。同样,来自 Angular2 文档:

    import { ModuleWithProviders }  from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    
    import { HeroListComponent }    from './hero-list.component';
    import { HeroDetailComponent }  from './hero-detail.component';
    
    const heroesRoutes: Routes = [
      { path: 'heroes',  component: HeroListComponent },
      { path: 'hero/:id', component: HeroDetailComponent }
    ];
    
    export const heroesRouting: ModuleWithProviders = RouterModule.forChild(heroesRoutes);
    

    Angular2 文档在大多数情况下都可以提供帮助,因为它是不断变化的 Angular2 API 的事实上的参考

    干杯!

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多