如何在Angular 2中通过routerLink获取参数?

如何在Angular 2中通过routerLink获取参数?

问题描述:

我想通过使用routerLink的URL传递一个值。并在另一页上读取该值。 像我有产品清单。在选择第一条记录时,该记录的标识传递到产品详细信息页面。读完productId后,我想显示该产品的详细信息。如何在Angular 2中通过routerLink获取参数?

那么如何传递并获取参数?

我是假设你有这样的代码:

{ path: 'product/:id', component: ProductDetailComponent } 

in ProductL北京时间模板

<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); 
} 

路由器文件:https://angular.io/docs/ts/latest/guide/router.html

在您的a标记上使用routerLink来标记url。

[routerLink]="['yourRouteHere', {'paramKey': paramValue}] 

为了得到它,你需要使用ActivatedRoute服务。将它注入组件并使用它的订阅方法。这里我route注射服务

this.route.params.subscribe(params => { 
    const id = Number.parseInt(params['paramKey']); 
} 

如果你想从路段使用.params,如果从查询字符串想别的参数,使用.queryParams

+0

thanx,但它给我错误。 – MohammedAshrafali

+0

但是'[routerLink] =“['yourRouteHere',{'paramKey':{'key':'value'}}]''' – Toolkit

1. 假设您的网址是HTP://abc.com/xyz和期望的结果是 HTP: //abc.com/zyx/users?id=1然后使用以下代码

<a [routerLink]="['user']" [queryParams]="{id: 1}" </a> 

2 .suppose网址是HTP://abc.com/xyz和您的期望的结果是HTP://abc.com/users ID = 1下面的代码

使用
<a [routerLink]="['/user']" [queryParams]="{id: 1}" </a>