如何在Angular 2中使用routerLink传递和获取参数? [英] How to pass and get parameter with routerLink in Angular 2?
问题描述
我想使用routerLink传递带有url的值.并在另一页上读取该值. 就像我有产品清单.在选择第一条记录时,该记录的ID会传递到产品详细信息页面.读完productId之后,我想显示该产品的详细信息.
I want to pass a value with url using routerLink. And read that value on another page. Like I have product list. On select of first record the id of that record pass to product detail page. After read that productId I want to show detail of that product.
那我该如何传递并获取参数?
So How can I pass and get the parameter?
推荐答案
我假设您有这样的代码:
I'm assuming you have some code like this:
{ path: 'product/:id', component: ProductDetailComponent }
在ProductList模板中
in ProductList template
<a [routerLink]="['/product', id]">Home</a>
或
<a [routerLink]="['/product', 5]">Home</a>
其中id
是变量,也许您将其循环了.
where id
is a variable, maybe you got it in a loop.
在ProductDetailComponent中:
in ProductDetailComponent:
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params
// (+) converts string 'id' to a number
.switchMap((params: Params) => this.yourProductService.getProductById(+params['id']))
.subscribe((product) => this.product = product);
}
路由器文档: https://angular.io/docs/ts/latest/guide/router.html
这篇关于如何在Angular 2中使用routerLink传递和获取参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!