我们期望实现的场景:从product list Component点击产品名称超链接时,能跳转到product detail Component,显示选中的product的明细信息。
在product detail Component引入路由相关的library:
import { ActivatedRoute } from ‘@angular/router’;
导入product sample data:
在product detail Component里定义一个名为product的property,同时通过将import的ActivatedRoute添加到Component的构造函数的参数里,实现注入的目的:
The ActivatedRoute is specific to each routed component that the Angular Router loads. It contains information about the route, its parameters, and additional data associated with the route.
By injecting the ActivatedRoute, you are configuring the component to use a service.
实现ngOnInit:
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.product = products[+params.get('productId')];
});
}
The route parameters correspond to the path variables you define in the route. The URL that matches the route provides the productId. Angular uses the productId to display the details for each unique product.
在product detail Component显示product property的信息:
<h2>Product Details</h2>
<div *ngIf="product">
<h3>{{ product.name }}</h3>
<h4>{{ product.price | currency }}</h4>
<p>{{ product.description }}</p>
</div>
效果如下:
跳转时的调试:
跳转时选中的product的索引,通过参数productId传入到product detail Component里:
要获取更多Jerry的原创文章,请关注公众号"汪子熙":