Angular 路由传参的几种方式

import { ActivatedRoute, Router }from '@angular/router';

private route: ActivatedRoute;
private router: Router ;

路由必填参数

// 路由配置
{ path: 'detail/:id', component: DetailComponent }

// 传参方式
<a [routerLink]="['/detail', detail.id]"></a>
this.router.navigate(['/detail', this.detail.id]);

// 读取参数
this.route.snapshot.paramMap.get('id');

// 页面路径
`http://localhost:4200/detail/1

路由可选参数

// 路由配置
{ path: 'detail', component: DetailComponent }

// 传参方式
<a [routerLink]="['/detail', {age: 18, male: true}]"></a>
this.router.navigate(['/detail',  {age: 18, male: true}]);

// 读取参数
this.route.snapshot.paramMap.get('age');
this.route.snapshot.paramMap.get('male');

// 页面路径
`http://localhost:4200/detail;age=18;male=true

路由查询参数

// 路由配置
{ path: 'detail', component: DetailComponent }

// 传参方式
<a [routerLink]="['/detail']" [queryParams]=" {age: 18, male: true}"></a>
this.router.navigate(['/detail'], {queryParams: {age: 18, male: true}});

// 读取参数
this.route.snapshot.queryParamMap.get('age');
this.route.snapshot.queryParamMap.get('male');

// 页面路径
`http://localhost:4200/detail?age=18&male=true

注意

[routerLink] 中的路径
如果以 / 开头,路由将从根路由开始查找
如果以 ./ 开头或没有使用 / ,则路由将从当前激活路由的子路由开始查找
如果以 ../ 开头,路由往上一级查找

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容