2017-09-25 90 views
0

我想要发送一个变量,只要按下list-profile html doc中提供的链接即可。当前的代码不起作用,并崩溃。如果需要,我可以提供更多细节。通过routerLink传递参数到一个新组件

列表profile.component.html

<div class="col col-sm-4 col-sm-offset-4"> 
    <ul id="list_of_users"> 
     <li class="list-group-item list-group-item-action" *ngFor="let user of users"><a [routerLink]="['/profile', user.id]" routerLinkActive="active" (click)="testFunc(user.id)">{{user.name}}</a></li> 
    </ul> 
</div> 

app.module.ts

const appRoutes: Routes = [ 
{ path: 'addProfile', component: AddProfileComponent }, 
{ path: 'listProfiles', component: ListProfilesComponent}, 
{ path: 'profile:id', component: ProfileComponent} 
]; 

回答

2

的路径更改为以下

const appRoutes: Routes = [ 
    { path: 'addProfile', component: AddProfileComponent }, 
    { path: 'listProfiles', component: ListProfilesComponent}, 
    { path: 'profile/:id', component: ProfileComponent} // change to this 
    ]; 

更新访问Value

import {ActivatedRoute} from '@angular/router'; 
... 

constructor(private route:ActivatedRoute){} 


ngOnInit(){ 
    this.route.params.subscribe(params => 
     console.log(params['id']; 
    ) 
} 

注意 - 如果您正在使用角(V4),请更改参数去paramMap

+0

它不会再崩溃!但我在哪里获取变量?在构造函数里面? – Amar

+0

内部构造函数或ngOnInit –

+0

你能提供代码示例吗?因为atm组件说:类'ProfileComponent'错误地实现了接口'OnInit'。财产'ngOnInit'的类型是可以相容的。类型'(id:string)=> void'不可分配类型'()=> void。 – Amar