Moh*_*ali 7 angular2-routing angular
我想使用routerLink传递一个带url的值.并在另一页上读取该值.就像我有产品清单.在选择第一条记录时,该记录的ID传递到产品详细信息页面.读完该产品之后,我想要显示该产品的详细信息.
那么如何通过并获取参数?
Tie*_*han 16
我假设你有这样的代码:
{ path: 'product/:id', component: ProductDetailComponent }
Run Code Online (Sandbox Code Playgroud)
在ProductList模板中
<a [routerLink]="['/product', id]">Home</a>
Run Code Online (Sandbox Code Playgroud)
要么
<a [routerLink]="['/product', 5]">Home</a>
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
路由器文件:https://angular.io/docs/ts/latest/guide/router.html
routerLink在a标记上使用以通过网址传递它.
[routerLink]="['yourRouteHere', {'paramKey': paramValue}]
Run Code Online (Sandbox Code Playgroud)
要获得它,您需要使用ActivatedRoute服务.将其注入您的组件并使用它的订阅方法.在这里,我route是注入的服务
this.route.params.subscribe(params => {
const id = Number.parseInt(params['paramKey']);
}
Run Code Online (Sandbox Code Playgroud)
如果要从路径段使用获取参数.params,否则如果您想从查询字符串中使用,请使用.queryParams
尝试这个:
步骤 1:在路由模块中
{ path: 'product/:id', component: ProductDetailComponent }
Run Code Online (Sandbox Code Playgroud)
步骤 2:将值发送到路由
<a [routerLink]="['/product', id]">Home</a> //say, id=5
Run Code Online (Sandbox Code Playgroud)
步骤 3:读取 ProductDetailComponent 中的值
首先注入ActivatedRoute的'@angular/router说route是注射服务。使用下面的代码内ngOnInit()方法来阅读它。
id = this.route.snapshot.paramMap.get('id');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34337 次 |
| 最近记录: |