How to pass and get parameter with routerLink in Angular 2?

孤街浪徒 提交于 2019-12-04 08:40:41

问题


I want to pass a value with url using routerLink. And read that value on another page. Like I have product list. On select of first record the id of that record pass to product detail page. After read that productId I want to show detail of that product.

So How can I pass and get the parameter?


回答1:


I'm assuming you have some code like this:

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

in ProductList template

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

or

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

where id is a variable, maybe you got it in a loop.

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

Router document: https://angular.io/docs/ts/latest/guide/router.html




回答2:


Use routerLink on your a tag for passing it by url.

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

To get it you need to use ActivatedRoute service. Inject it into your component and use it's subscribe method. Here my route is the injected service

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

If you want to get parameters from the route segment use .params, else if you want from query string, use .queryParams




回答3:


Try this:

Step-1: In routing module

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

Step-2: Send the value to routing

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

Step-3: Read the value in ProductDetailComponent

First inject ActivatedRoute from '@angular/router and say route is the injected service. Use the below code inside ngOnInit() method to read it.

id = this.route.snapshot.paramMap.get('id');



回答4:


  1. Suppose your url is http://mit.edu/dashboard and desired result is http://mit.edu/dashboard/user?id=1 then use below code
<a [routerLink]="['user']" [queryParams]="{id: 1}" </a>
  1. Suppose your url is http://mit.edu/dashboard and your desired result is http://mit.edu/user?id=1 then use below code ["Difference is /Dashobard" missing here from url]
<a [routerLink]="['/user']" [queryParams]="{id: 1}" </a>


来源:https://stackoverflow.com/questions/42201703/how-to-pass-and-get-parameter-with-routerlink-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!