1

我對angular2中的路由有疑問。今天,我正在使用與angular2官方教程相同的示例。 的代碼是這樣的(file link):在angular2中組織路由的最佳方式

// 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); 

我的問題是。如果我有多個垃圾,我會得到一堆組件(如實體/列表,實體/添加,實體/編輯,實體/顯示)

那麼,該如何解決?組織我的路線而不創建凌亂組件的最佳方式是什麼?

回答

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

乾杯事實上的參考!

+1

這正是我所期待的! 我看到了這個結構,這是解決這個部分: https://angular.io/docs/ts/latest/guide/router.html#the-heroes-app-code 非常感謝! –

相關問題