2017-07-28 64 views
1

從Angular文檔中,路由示例的路由在與其嘗試路由的模塊(AppModule)相同的模塊內完成。像這樣:Angular:應該在自己的模塊中完成路由嗎?

const appRoutes: Routes = [ 
    { path: 'crisis-center', component: CrisisListComponent }, 
    { path: 'hero/:id',  component: HeroDetailComponent }, 
    { 
    path: 'heroes', 
    component: HeroListComponent, 
    data: { title: 'Heroes List' } 
    }, 
    { path: '', 
    redirectTo: '/heroes', 
    pathMatch: 'full' 
    }, 
    { path: '**', component: PageNotFoundComponent } 
]; 

@NgModule({ 
    imports: [ 
    RouterModule.forRoot(
     appRoutes, 
     { enableTracing: true } // <-- debugging purposes only 
    ) 
    // other imports here 
    ], 
    ... 
}) 
export class AppModule { } 

但是,style guide for Angular提到使用路由模塊。因此,爲AppRoutingModule添加一個文件,並在AppModule中導入模塊,而不是簡單地在AppModule中完成路由。從我可以從各種教程,指南等獲得的內容中,將使用AppRoutingModule。

然而,我仍然對我應該使用哪種結構感到困惑。我被教導說,軟件結構中的模塊應該儘可能少地依賴,以便它們可以很容易地部署和/或重用。但是沒有一個單獨的模塊用於100%依賴於其他模塊的路由,而不是這個概念?

來自AppRoutingModule的路由不適用於AppModule旁邊的任何東西。那麼爲什麼在路由使用的每個組件上重複導入,而不是在AppModule中創建路由?

是否有我應該用於我的項目(以及爲什麼)的具體結構,還是僅僅受個人喜好,我想如何構建我的項目?

+0

_or是否只有個人偏好我想如何構建我的項目?_是 –

回答

0

如果你使用模塊系統,你可以做一些優化步驟。 在例如:

  1. 懶惰路由器
  2. 單獨的模塊噴射

可以與網絡檢查它。加載新模塊後JS更新。

這是很好的AOT編譯,你可以有一個最快的負載沒有任何依賴。

如果您需要共享模塊,您可以創建模塊以及導入和導出模塊如何在所有應用程序中使用時如何使用模態窗口和其他模塊。

純組分壞樣式代碼,因爲你不能分開你的項目到另一個項目,並與聯依賴大系統大monolyte項目。

你可以看到調製在我家項目系統 - https://github.com/Adventure-RPG/Adventure-Client/tree/master/src

0

這是可以做到無論哪種方式,都可以歸結爲是偏好。爲了可維護性和日益增長的應用,更容易將它們分開。

創建一個app.routing文件來定義路由,保持所有路由整潔。例如,我有一個app.routing文件的應用程序,然後導入到app.module文件中。 任何新的組件或路由都會簡單地添加到app.routing文件中,並且此文件具有簡單的單一用途。

app。路由

import {RouterModule, Routes} from '@angular/router'; 
import {LoginPage} from './pages/login.page'; 
import {AnotherPageComponent} from './pages/anotherPage.component'; 
import {DashboardPageComponent} from './pages/dashboard.page'; 
... 

// Define the routes for this application 
export const appRoutes: Routes = [ 
    {path: 'dashboard', component: DashboardPageComponent}, 
    {path: 'another', component: AnotherPageComponent} 
    {path: '**', component: LoginPage} 
]; 
export const appRoutingProviders: any[] = []; 
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true}); 

然後在app.module,只需導入您的appRoutingProviders和路由常數。

app.module

import {appRoutingProviders, routing} from './app.routing'; 

imports: [ 
    routing, 
    ...], 
providers: [ 
    appRoutingProviders, 
    ..] 

同樣,這完全取決於你如何構建應用程序,但超前的思維,你想這是因爲簡單地維持。最好的方法 - 按照你的理解去做,一般來說這會讓事情變得更簡單。

較大的應用程序可能會將路由進一步分解爲可以延遲加載的子模塊,但這是另一回事。

tl; dr - 它取決於您,因爲沒有是或否的答案。

相關問題