通过routerLink将参数传递给新组件

时间:2017-09-25 07:16:41

标签: html angular parameters routing components

我想按下list-profile html doc中提供的链接后发送一个变量。当前代码不起作用,它崩溃了。如果需要,我可以提供更多细节。

列表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}
];

1 个答案:

答案 0 :(得分:3)

将路线更改为以下

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

更新以访问值

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

constructor(private route:ActivatedRoute){}


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

注意 - 如果您使用的是Angular(v4),请将param更改为paramMap