2017-08-27 88 views
1

我在Angular 4中路由時需要幫助。我想要顯示這樣的URL。本地主機:4200 /用戶/ 1如果我點擊第一個用戶的查看詳細信息。我對如何解決這個問題有點困惑。我在下面的代碼中盡力而爲,但它仍然不起作用。在Angular 4中使用ID路由

APP-routing.module.ts

const appRoutes: Routes = [ 
    { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, 
    { path: 'dashboard', component: DashboardComponent }, 
    { path: 'user', component: UserComponent, children: [ 

     { path: 'create-new-user', component: CreateNewUserComponent }, 
     { path: 'user-list', component: UserListComponent }, 
     { path: 'user-detail/:id', component: UserDetailComponent }, 

]}, 
]; 


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

} 
+0

你說的不工作呢? – Daniel

+0

我的意思是我不能去這個URL本地主機:4200 /用戶/ 1。希望您能夠幫助我。 – Joseph

回答

1

應該是這樣的

ViewDetail(index : any){ 
    this.router.navigate(['/user-detail', index]); 
    } 

如果你想爲上市/user/1然後改變路由器配置來匹配網址名稱i:e而不是user-detail更改爲user

UPDATE

雅有模板線改變這種

<td><button class="btn btn-primary" style="cursor: pointer;" (click)="ViewDetail(i)">View</button></td> // it should be i instead of index 
+0

如何在其他組件和user-list.html – Joseph

+0

在用戶列表中,您尚未定義動態路由請參閱您的路由器配置'{路徑:'用戶列表',組件:UserListComponent},'沒有':id '在這裏。從用戶列表中您將導航到用戶詳細信息那裏你會看到url的變化 –

+0

它工作@Joseph? –

1

我覺得你ViewDetail()方法需要索引參數。 例如

public ViewDetail(index: number) 
{ 
    this.index = index; 
    ... 
} 

路由本身有一個很好的例子here。 他們使用下面的路由定義:

const routes: Routes = [ 
    ... 
    { path: 'detail/:id', component: HeroDetailComponent }, 
    ... 
]; 

至於打字稿代碼。

gotoDetail(): void { 
    this.router.navigate(['/detail', this.selectedHero.id]); 
} 

所以,我認爲你在那裏是正確的軌道。

我認爲這只是索引沒有設置。

+0

感謝您的幫助:) – Joseph

+0

@bvdb,你是如何在'gotoDetail()'方法中定義'router'的? – Juniuz

1

在你的路由文件

const appRoutes: Routes = [ 
     { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, 
    { path: 'dashboard', component: DashboardComponent }, 
    { path: 'user', component: UserComponent, children: [ 
     { path: 'create-new-user', component: CreateNewUserComponent }, 
    { path: 'user-list', component: UserListComponent }, 
    { path: ':id', component: UserDetailComponent }, 
]} 
]; 

在您看來的方法做這樣的

ViewuserDetail(user_id : any){ 
    let url: string = "/user/" + user_id 
     this.router.navigateByUrl(url); 
    } 

在模板

<td><button class="btn btn-primary" (click)="ViewuserDetail(user_object.id)">View</button></td>