2016-08-24 35 views
11

我試圖做一個項目裏面另一個路由器插座一個路由器出口路由器出口:角2,RC5內其它路由器出口

它會像這樣:

在第一路由器出口它將具有兩個視圖:

  • AUTH組分(/登錄)

  • 管理員組分(/管理員)

然後在第二齣口將是管理組件內,與它自己的路由,這將使得這些:

  • 儀表板(/管理員)

  • 輪廓(/管理/輪廓)

  • 用戶(/管理/用戶)

現在,在Angular 2文檔中,我可以看到他們使用模塊進行了這種實現。但我不想使用多個模塊(或我必須?)。

有沒有辦法讓這個實現沒有分離模塊?

我想要一個管理區域的默認組件,這就是爲什麼我想要第二個路由器插座,例如:儀表板將具有HeaderComponent,LeftNavComponent和DashboardCompoent。但是配置文件頁面也會包含所有這些HeaderComponent和LeftNavComponent,並且唯一會改變的是ProfileComponent,所以它將具有基本相同的結構。我想我不需要爲每個不同的管理頁面重複每次導入。我想只有一個主要管理組件,它將基於當前路線創建動態內容。

我已經在互聯網上試過並搜索了很多,但我能找到的唯一例子是來自官方的Angular 2文檔。但他們正在用多個模塊來實現這一點。

+1

模塊是延遲加載所必需的,據我所知,在下一次更新之後將是必需的,因爲不推薦使用「Component.pipes」和「Component.directives」。 –

+0

很高興知道!昨天我問自己爲什麼他們沒有使用「。(Angular 2 documentation)例子中的「directives」屬性,所以現在一切都將從模塊中導入,而不是從組件中導入,如果是這樣的話,還有另外一個理由來使用模塊!Hahahah。 –

回答

17

雖然推薦模塊,但它們對於任何路線導航都是可選的。

您可以像下面那樣配置路由而不需要任何模塊。

app.routing

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

     import { DashboardComponent, 
     AdminComponent, 
     ProfileComponent, 
     UsersComponent 
     } from './app.component'; 

     const appRoutes: Routes = [ 
     { 
     path: '', 
     redirectTo: '/dashboard/admin/users', 
     pathMatch: 'full' 
     }, 
     { 
     path: 'dashboard', 
     component: DashboardComponent, 
     children:[ 
     { 
     path : 'admin', 
     component: AdminComponent, 
     children:[ 
      { 
      path : 'users', 
      component: UsersComponent 
      }, 
      { 
      path : 'profile', 
      component: ProfileComponent 
      } 
     ] 
     } 
     ] 
    } 
    ]; 

    export const routing = RouterModule.forRoot(appRoutes); 

部件

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

@Component({ 
    selector: 'my-app', 
    template: ` 
    <h3 class="title">Routing Deep dive</h3> 
    <hr /> 
    <router-outlet></router-outlet> 
    ` 
}) 
export class AppComponent { 
} 


@Component({ 
    template: ` 
    <h3 class="title">Dashboard</h3> 
    <nav> 
    </nav> 
    <hr /> 
    <router-outlet></router-outlet> 
    ` 
}) 
export class DashboardComponent { 
} 

@Component({ 
    template: ` 
    <h3 class="title">Admin</h3> 
    <nav> 
     <a routerLink="users" routerLinkActive="active" >Users</a> 
     <a routerLink="profile" routerLinkActive="active" >Profile</a> 
    </nav> 
    <hr /> 
    <router-outlet></router-outlet> 
    ` 
}) 
export class AdminComponent { 
} 

@Component({ 
    template: ` 
    <h3 class="title">Profile</h3> 
    ` 
}) 
export class ProfileComponent { 
} 

@Component({ 
    template: ` 
    <h3 class="title">Users</h3> 
    <hr /> 
    ` 
}) 
export class UsersComponent { 
} 

這裏是Plunker !!

希望這有助於!

+0

謝謝在發佈這個問題後,我已經閱讀了angular 2文檔,現在我明白瞭如何使用所有這些模塊,路由和子路由,我想我會這樣做。一個我期望的,我想要兩個路由器插座,一個在/ login和/ admin之間切換,另一個插座將在/ admin之間導航,這些屬於/ admin路徑。但是,由於你的例子,現在我可以理解了如何修改它使一切正常工作,所以我再次感謝您的幫助! –

+0

@ThiagoYoithi:很高興知道它有幫助...乾杯! –

+0

@günter-zöchbauer任何示例ta延遲加載模塊的國王優勢。 – Patrice