---
# System prepended metadata

title: Day28 【牙起來】 路由接收參數 - Routing

---

# Day28 【牙起來】 路由接收參數 - Routing

## 路徑參數(Path Params)

### 接收方

在路由上定義好接收的**路徑參數名稱** ex: `/:id`
修改 `app-routing.module.ts`

```typescript=
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { StoreComponent } from './store/store.component';
import { RoleComponent } from './role/role.component';

const routes: Routes = [
  { path: 'store', component: StoreComponent },
  { path: 'role', component: RoleComponent },
  { path: 'role/:id', component: RoleComponent },
];


@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}
```


修改`role.component.ts`
```typescript=
...

  constructor(private route: ActivatedRoute) {
  }

  ngOnInit(): void {
    console.log(this.route.snapshot.paramMap.get('id'));
  }
```


> `http://localhost:4200/role/6556`
> ![](https://i.imgur.com/hUUoQSH.png)
> 
> 當帶入路徑參數時，
> 可透過`route.snapshot.paramMap.get('id')`取得變數`id`



### 傳送方

```typescript=
constructor(
    private router: Router,
) {}

...

this.router.navigate(['/pages/surveyInfoStudent/', id]).then();
```


## 接收查詢參數(Query Params)

修改 `role.component.ts`
```typescript=
...

export class RoleComponent implements OnInit {

  atk = 0;
  def = 0;

  constructor(private route: ActivatedRoute, private router: Router) {
  }

  ngOnInit(): void {
    this.route.queryParams.subscribe(
      params => {
        this.atk = params['atk'];
        this.def = params['def'];
      }
    )
  }
}
```

修改 `role.component.html`
```html=
<div>勇者，你的攻擊力為：{{atk}}</div>
<div>勇者，你的防禦力：{{def}}</div>
```


> `http://localhost:4200/role?atk=15&def=6`
> ![](https://i.imgur.com/Y5vdzRB.png)
>
> 當帶入查詢參數時，
> 可透過`route.queryParams` 取得key、value對應物件的參數







