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中新建带参数路由

在app.component.html中传递参数

在product.component.ts中接受参数

参数快照和参数订阅

参数快照

参数订阅

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

Last updated

Was this helpful?