2017-05-08 65 views
1

我嘗試將永久鏈接添加到我的角度2應用程序,但我還沒有找到方法。Angular 2 - 如何添加永久鏈接?

我的應用程序,routing.module.ts:

const routes: Routes = [ 
    { path: '', pathMatch: 'full', component: TagelerComponent }, 
    { path: 'tageler', component: TagelerListComponent }, 
    { path: 'tageler-details/:id', component: TagelerDetailsComponent }, 
    { path: 'group/:id', component: GroupDetailsComponent }, 
    { path: 'tageler/admin', component: AdminComponent }, 
]; 

@NgModule({ 
    imports: [ RouterModule.forRoot(routes) ], 
    exports: [ RouterModule ] 
}) 
export class AppRoutingModule {} 

我的代碼如下所示:

<div *ngFor="let group of groups | groupTypeFilter: 'Trupp' "> 
    <a routerLink="/group/{{group._id}}"> 
     <li class="list-group-item"> 
     {{group.name}} 
     </li> 
    </a> 
</div> 

在這個例子中的URL是這樣的:http://localhost:4200/group/5910c2282249261cc61d0a7e

代替組ID,我想在不更改路由的情況下顯示組的名稱(例如狗),因此URL更改爲:'http://localhost:4200/group/dogs'。

我是Angular 2的新手,所以我不確定這是否真的有可能。

如果有人能幫助我,我會很高興!

回答

0

答案是你不能與在routerLink名稱更換ID,然後通過ID查詢組,假設用戶打開一個新的標籤和輸入的URL

http://localhost:4200/group/dogs

該應用程序將加載和你有唯一的參考是dogs,身份證從哪裏來?除非你已經定義了一個返回給定組名的id的字典,或者使用一些黑魔法

但是,如果你只讓用戶通過它的父級訪問詳細信息頁,那麼你可以通過組通過使用共享服務並將路由器鏈接設置爲group.name

<div *ngFor="let group of groups | groupTypeFilter: 'Trupp' "> 
    <a [routerLink]="shared.setGroupLink(group)"> 
    <li class="list-group-item"> 
     {{group.name}} 
    </li> 
    </a> 
</div> 

constructor(public shared: SharedService) { } 

SharedService

export class SharedService{ 

    currGroupId: number; 

    constructor() { } 

    setGroupLink(group) { 
     // you can pass the object as a whole but I'll use `group.id` in this example 
     // this.currGroup = group; 
     this.currGroupId = group.id; 
     return '/group/' + group.name; 
    } 
} 

GroupDetailsComponent

groupId: number; 

constructor(public shared: SharedService) { } 

ngOnInit() { 
    this.groupId = this.shared.currGroupId; 
} 

注:這種做法不會,如果用戶輸入http://localhost:4200/group/dogs因爲groupId是不確定的工作

的方式,避免與下劃線_前綴的變量的名字,檢查Angular Style Guide

+0

謝謝,我會努力的!你知道如果用戶輸入'http:// localhost:4200/group/dogs',是否還有一種方法也可以工作? – Ramona