【问题标题】:Pass parameter through routerLink to a new component通过 routerLink 将参数传递给新组件
【发布时间】:2018-03-06 02:07:37
【问题描述】:

我想在按下 list-profile html 文档中提供的链接后发送一个变量。当前代码不起作用并且崩溃。如果需要,我可以提供更多详细信息。

list-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}
];

【问题讨论】:

    标签: html angular parameters routing components


    【解决方案1】:

    将路由更改为以下

       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

    【讨论】:

    • 它不再崩溃了!但是我在哪里获取变量?在构造函数内部?
    • 在构造函数内部或 ngOnInit
    • 您能提供代码示例吗?因为 atm 组件说:“ProfileComponent”类错误地实现了接口“OnInit”。属性“ngOnInit”的类型不兼容。类型 '(id: string) => void' 不可分配类型 '() => void。
    • 你需要在组件中实现onInit然后使用它,我更新了答案
    • 做到了!谢谢
    猜你喜欢
    • 2019-04-12
    • 2017-10-19
    • 2017-11-29
    • 1970-01-01
    • 2016-04-28
    • 2021-07-18
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多