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

后端 未结 5 960
终归单人心
终归单人心 2021-02-06 06:30

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

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 07:07

    I'm assuming you have some code like this:

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

    in ProductList template

    Home
    

    or

    Home
    

    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

提交回复
热议问题