3.2在路由时传递数据

路由传递数据有以下3种方式:

  1. 在查询参数中传递数据 /product?id=1&name=2→ActivatedRoute.queryParams[id]

  2. 在路由路径中传递数据 {path:/product/:id} → /product/1 → ActivatedRoute.params[id]

  3. 在路由配置中传递数据 {path : /product, component: ProductComponent, data: [{isProd:true}] } → ActivatedRoute.data[0][isProd]

实战

实战:在查询参数中传参

在app.component.html中传递参数

<a [routerLink]="['/product']" [queryParams]="{id:1}">带参路由</a>

在product.component.ts中接受参数

  productId: number;

  constructor(private routeInfo: ActivatedRoute) {
  }

  ngOnInit() {
    this.productId = this.routeInfo.snapshot.queryParams['id'];
  }

实战:在路由路径中传递数据

在app-routing.module.ts中新建带参数路由

{path: 'product/:id', component: ProductComponent}
{path: 'product/路由变量', component: ProductComponent}

在app.component.html中传递参数

<a [routerLink]="['/product',1]">商品详情带参</a>
<a [routerLink]="['路由URL',路由变量]">商品详情带参</a>

在product.component.ts中接受参数

  productId: number;

  constructor(private routeInfo: ActivatedRoute) {
  }

  ngOnInit() {
    this.productId = this.routeInfo.snapshot.params['id'];
  }

参数快照和参数订阅

参数快照

this.productId = this.routeInfo.snapshot.params['id'];

参数订阅

this.routeInfo.params.subscribe((params: Params) => this.productId = params['id']);

提示:如果路由会路由自身,必须使用路由订阅。

Last updated

Was this helpful?