Angular 路由传参的几种方式

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

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

1.必填路由参数

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

// 路由跳转方式
<a [routerLink]="['/detail', item.id]">...</a>
this.router.navigate(['/detail', this.id]);

// 获取路由参数
this.route.snapshot.paramMap.get('id');

// 浏览器 url 呈现
'http://localhost:4200/detail/1'

2.可选路由参数

// 路由配置
{ path: 'list', component: ListComponent }

// 路由跳转方式
<a [routerLink]="['/list', {type: 1, sort: true}]">...</a>
this.router.navigate(['/list', {type: 1, sort: true}]);

// 获取路由参数
this.route.snapshot.paramMap.get('type');
this.route.snapshot.paramMap.get('sort');

// 浏览器 url 呈现
'http://localhost:4200/list;type=1;sort=true'

3.路由查询参数

// 路由配置
{ path: 'list', component: ListComponent }

// 路由跳转方式
<a [routerLink]="['/list']" [queryParams]="{type: 1, sort: true}">...</a>
this.router.navigate(['/list'], {queryParams: {type: 1, sort: true}});

// 获取路由参数
this.route.snapshot.queryParamMap.get('type');
this.route.snapshot.queryParamMap.get('sort');

// 浏览器 url 呈现
'http://localhost:4200/list?type=1&sort=true'

注意

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

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