2016-05-17 54 views
2

我正在構建一個簡單的應用程序,其中某人可以通過表單中的電子郵件搜索用戶,然後查看與該用戶關聯的各種數據。Angular 2中的候選發佈組件路由器

對於頂部AppComponent分量I具有如下路線:

@Routes([ 
    {path: '/:name', component: CustomerComponent}, 
    {path: '/search', component: SearchComponent} 
]) 

路徑對應於形式來搜索客戶和/搜索:名稱路徑旨在是用於顯示該數據顧客。

我的想法是讓客戶組件有一些基本的佈局,也許事情,比如用戶的個人資料圖片,然後有鏈接到一個客戶檔案的,像這樣的不同部分:

@Routes([ 
    {path: '/profile', component: CustomerProfileComponent}, 
    {path: '/loyalty', component: CustomerLoyaltyComponent}, 
    {path: '/coupons', component: CustomerCouponsComponent}, 
    {path: '/settings', component: CustomerSettingsComponent} 
]) 

和HTML:

<div> 
    <span> 
     <a [routerLink]="['./profile']">Profile</a> 
     <a [routerLink]="['./loyalty']">Loyalty</a> 
     <a [routerLink]="['./coupons']">Coupons</a> 
     <a [routerLink]="['./settings']">Settings</a> 
    </span> 
</div> 
<div> 
    <router-outlet></router-outlet> 
</div> 

我希望這個佈局將讓我有網址,如:

/search 
/joe/profile 
/joe/loyalty 
/joe/coupons 
/joe/coupons/14/ 
/joe/coupons/14/edit 
...etc 

我遇到的問題是,似乎在子路由器中,我無法使用RouteSegment獲取用戶電子郵件。例如,內CustomerProfileComponent我實現OnActivate和嘗試以下操作:

routerOnActivate(curr: RouteSegment) { 
    let name = curr.getParam('name'); 
    console.log("profile says " + name); 
} 

然而,這種打印的個人資料說不確定的。「我想這是因爲:名稱路由參數不直接屬於CustomerComponent,而是屬於AppComponent中的路由。

我希望能夠從這些視圖中的每一個的RouteSegment中獲取名稱,然後可以使用它來點擊某個API來獲取有關該用戶的特定數據。

我讀過這樣一種方法:通過擁有像'當前用戶'變量之類的東西來共享狀態數據並將其注入到子路由中的所有組件中。

但是,我認爲如果我不需要以這種方式跨組件共享狀態,它會使應用程序更簡單。

有沒有什麼辦法可以從路線上得到名稱,或者有沒有更好的方法?

+2

嗨,你可以發表plunker你的代碼?在angular2路由器上沒有太多的文檔,你似乎已經知道了 – user2202911

回答

0

您需要routeLink添加信息如下

<a [routerLink]="['./profile', profile.name ]">Profile</a> 

其中profile是財產組件

還可通過網址將/profile/joelayout/joe