如何在Angular 2中使用routerLink传递和获取参数?

问题描述 投票:5回答:4

我想使用routerLink传递一个带url的值。并在另一页上读取该值。就像我有产品清单。在选择第一条记录时,该记录的ID传递到产品详细信息页面。读完该产品之后,我想要显示该产品的详细信息。

那么如何通过并获取参数?

angular angular2-routing
4个回答
16
投票

我假设你有这样的代码:

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

在ProductList模板中

<a [routerLink]="['/product', id]">Home</a>

要么

<a [routerLink]="['/product', 5]">Home</a>

其中id是一个变量,也许你在一个循环中得到它。

在产品详细信息组件中

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


6
投票

routerLink标签上使用a通过url传递它。

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

要获得它,您需要使用ActivatedRoute服务。将其注入您的组件并使用它的订阅方法。在这里,我的route是注入的服务

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

如果你想从路线段获取参数使用.params,否则如果你想从查询字符串中使用.queryParams


1
投票
  1. 假设您的网址是http://mit.edu/dashboard,所需的结果是http://mit.edu/dashboard/user?id=1然后使用下面的代码
<a [routerLink]="['user']" [queryParams]="{id: 1}" </a>
  1. 假设你的网址是http://mit.edu/dashboard,你想要的结果是http://mit.edu/user?id=1然后使用下面的代码[url这里缺少“差异是/ Dashobard”]
<a [routerLink]="['/user']" [queryParams]="{id: 1}" </a>

0
投票

试试这个:

步骤1:在路由模块中

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

步骤2:将值发送到路由

<a [routerLink]="['/product', id]">Home</a> //say, id=5

步骤3:读取ProductDetailComponent中的值

首先从ActivatedRoute注入'@angular/router,并说route是注射服务。使用ngOnInit()方法中的以下代码来读取它。

id = this.route.snapshot.paramMap.get('id');
© www.soinside.com 2019 - 2024. All rights reserved.