【发布时间】:2017-02-13 10:22:42
【问题描述】:
我想使用 routerLink 传递一个带有 url 的值。并在另一页上阅读该值。 就像我有产品清单一样。在选择第一条记录时,该记录的 ID 传递到产品详细信息页面。阅读该 productId 后,我想显示该产品的详细信息。
那么如何传递和获取参数呢?
【问题讨论】:
我想使用 routerLink 传递一个带有 url 的值。并在另一页上阅读该值。 就像我有产品清单一样。在选择第一条记录时,该记录的 ID 传递到产品详细信息页面。阅读该 productId 后,我想显示该产品的详细信息。
那么如何传递和获取参数呢?
【问题讨论】:
我假设你有一些这样的代码:
{ path: 'product/:id', component: ProductDetailComponent }
在产品列表模板中
<a [routerLink]="['/product', id]">Home</a>
或
<a [routerLink]="['/product', 5]">Home</a>
id 是一个变量,也许你在循环中得到它。
在 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);
}
【讨论】:
在您的a 标签上使用routerLink 通过url 传递它。
[routerLink]="['yourRouteHere', {'paramKey': paramValue}]
要获得它,您需要使用ActivatedRoute 服务。将其注入您的组件并使用它的 subscribe 方法。这里我的route 是注入的服务
this.route.params.subscribe(params => {
const id = Number.parseInt(params['paramKey']);
}
如果你想从路由段获取参数,使用.params,否则如果你想从查询字符串,使用.queryParams
【讨论】:
[routerLink]="['yourRouteHere', {'paramKey': {'key':'value'}}]
试试这个:
Step-1:在路由模块中
{ path: 'product/:id', component: ProductDetailComponent }
步骤 2:将值发送到路由
<a [routerLink]="['/product', id]">Home</a> //say, id=5
Step-3:读取 ProductDetailComponent 中的值
首先从'@angular/router 注入ActivatedRoute 并说route 是注入的服务。使用ngOnInit()方法中的以下代码来阅读它。
id = this.route.snapshot.paramMap.get('id');
【讨论】:
- 假设您的网址是 http://mit.edu/dashboard 并且期望的结果是 http://mit.edu/dashboard/user?id=1 然后使用下面的代码
<a [routerLink]="['user']" [queryParams]="{id: 1}" </a>
- 假设你的 url 是 http://mit.edu/dashboard 并且你想要的结果是 http://mit.edu/user?id=1 然后使用下面的代码 ["Difference is /Dashobard"网址中缺少这里]
<a [routerLink]="['/user']" [queryParams]="{id: 1}" </a>
【讨论】:
你可以在.html使用这个
[routerLink]="['/trips/display/' + item.trip, {'paramKey': 'application'}]"
在.ts 中,您可以使用它来恢复参数
this.id = this.route.snapshot.params['id'];
const param = this.route.snapshot.params['paramKey'];
【讨论】: