如何在Angular 2中使用routerLink传递和获取参数? [英] How to pass and get parameter with routerLink in Angular 2?
本文介绍了如何在Angular 2中使用routerLink传递和获取参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 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 }
在产品列表模板中
<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屋!
查看全文