import { Router, ActivatedRoute } from '@angular/router';
constructor(
private router: Router,
private route: ActivatedRoute,
) { }
1.必填路由參數(shù)
// 路由配置
{ path: 'detail/:id', component: DetailComponent }
// 路由跳轉(zhuǎn)方式
<a [routerLink]="['/detail', item.id]">...</a>
this.router.navigate(['/detail', this.id]);
// 獲取路由參數(shù)
this.route.snapshot.paramMap.get('id');
// 瀏覽器 url 呈現(xiàn)
'http://localhost:4200/detail/1'
2.可選路由參數(shù)
// 路由配置
{ path: 'list', component: ListComponent }
// 路由跳轉(zhuǎn)方式
<a [routerLink]="['/list', {type: 1, sort: true}]">...</a>
this.router.navigate(['/list', {type: 1, sort: true}]);
// 獲取路由參數(shù)
this.route.snapshot.paramMap.get('type');
this.route.snapshot.paramMap.get('sort');
// 瀏覽器 url 呈現(xiàn)
'http://localhost:4200/list;type=1;sort=true'
3.路由查詢參數(shù)
// 路由配置
{ path: 'list', component: ListComponent }
// 路由跳轉(zhuǎn)方式
<a [routerLink]="['/list']" [queryParams]="{type: 1, sort: true}">...</a>
this.router.navigate(['/list'], {queryParams: {type: 1, sort: true}});
// 獲取路由參數(shù)
this.route.snapshot.queryParamMap.get('type');
this.route.snapshot.queryParamMap.get('sort');
// 瀏覽器 url 呈現(xiàn)
'http://localhost:4200/list?type=1&sort=true'
注意
[routerLink]
中的路徑
如果以 / 開頭汉矿,路由將從根路由開始查找
如果以 ./ 開頭或沒有使用 / 崎坊,則路由將從當(dāng)前激活路由的子路由開始查找
如果以 ../ 開頭洲拇,路由往上一級查找