# 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` >  > > 當帶入路徑參數時, > 可透過`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` >  > > 當帶入查詢參數時, > 可透過`route.queryParams` 取得key、value對應物件的參數
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up