Angular路由跳转时,如何传递信息

时间:2022-07-23
本文章向大家介绍Angular路由跳转时,如何传递信息,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我们期望实现的场景:从product list Component点击产品名称超链接时,能跳转到product detail Component,显示选中的product的明细信息。

在product detail Component引入路由相关的library:

import { ActivatedRoute } from ‘@angular/router’;

导入product sample data:

在product detail Component里定义一个名为product的property,同时通过将import的ActivatedRoute添加到Component的构造函数的参数里,实现注入的目的:

The ActivatedRoute is specific to each routed component that the Angular Router loads. It contains information about the route, its parameters, and additional data associated with the route. By injecting the ActivatedRoute, you are configuring the component to use a service.

实现ngOnInit:

ngOnInit() {
  this.route.paramMap.subscribe(params => {
    this.product = products[+params.get('productId')];
  });
}

The route parameters correspond to the path variables you define in the route. The URL that matches the route provides the productId. Angular uses the productId to display the details for each unique product.

在product detail Component显示product property的信息:

<h2>Product Details</h2>

<div *ngIf="product">
  <h3>{{ product.name }}</h3>
  <h4>{{ product.price | currency }}</h4>
  <p>{{ product.description }}</p>

</div>

效果如下:

跳转时的调试:

跳转时选中的product的索引,通过参数productId传入到product detail Component里: