> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/qian-duan/angular/3.2-zai-lu-you-shi-chuan-di-shu-ju.md).

# 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中传递参数

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

在product.component.ts中接受参数

```typescript
  productId: number;

  constructor(private routeInfo: ActivatedRoute) {
  }

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

### 实战：在路由路径中传递数据

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

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

在app.component.html中传递参数

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

在product.component.ts中接受参数

```typescript
  productId: number;

  constructor(private routeInfo: ActivatedRoute) {
  }

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

## 参数快照和参数订阅

参数快照

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

参数订阅

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

> 提示：如果路由会路由自身，必须使用路由订阅。
