随笔 - 432  文章 - 0  评论 - 15  阅读 - 63万

angular 路由跳转以及传参的几种方式

通过域名跳转的方式获取参数(http://localhost:4200/second/110?productId=1&title=moon)

这种方式配置路由,其中:id是必需的参数,其它的是可配的,写在?后面:

1
{ path: 'second/:id', component: SecondComponent },

  

通过ts代码跳转:
1
this.router.navigate(['/second',110], { queryParams: { productId: '1', title: 'moon' } });

  获取【:id】参数的方式:

1
2
constructor(private route: ActivatedRoute, private router: Router) { }
var id = this.route.snapshot.paramMap.get('id');

  

在comoent中需要这么获取‘?’ 后面的参数,将参数写在queryParams里
1
this.router.navigate(['/second',110], { queryParams: { productId: '1', title: 'moon' } });

  

通过ActivatedRoute来获取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
constructor(private route: ActivatedRoute, private router: Router) { }
 
ngOnInit() {
 
  var id = this.route.snapshot.paramMap.get('id');
  this.name = id;
  console.log(id);
   
  this.route.queryParams.subscribe(param => {
    console.log(param);
    console.log(param.title);
    console.log(param['title']);
    console.log(param.productId);
    console.log(param['productId']);
  });
}

  


1.this.router.navigate(['user', 1]); 
以根路由为起点跳转

2.this.router.navigate(['user', 1],{relativeTo: route}); 
默认值为根路由,设置后相对当前路由跳转,route是ActivatedRoute的实例,使用需要导入ActivatedRoute

3.this.router.navigate(['user', 1],{ queryParams: { id: 1 } }); 
路由中传参数 /user/1?id=1

4.this.router.navigate(['view', 1], { preserveQueryParams: true }); 
默认值为false,设为true,保留之前路由中的查询参数/user?id=1 to /view?id=1

5.this.router.navigate(['user', 1],{ fragment: 'top' }); 
路由中锚点跳转 /user/1#top

6.this.router.navigate(['/view'], { preserveFragment: true }); 
默认值为false,设为true,保留之前路由中的锚点/user/1#top to /view#top

7.this.router.navigate(['/user',1], { skipLocationChange: true }); 
默认值为false,设为true路由跳转时浏览器中的url是跳转前的路径,但是传入的参数依然有效

8.this.router.navigate(['/user',1], { replaceUrl: true }); 
未设置时默认为true,设置为false路由不会进行跳转

9.页面里url路转写法

1
2
3
4
5
<nav>
    <a routerLink="/heroes/{{id}}">点击查看文章详情</a>
    <!--数组格式传参,注是第二种试的routerLink是用[]包括-->
    <a [routerLink]="['/heroes', num]">点击查看文章详情</a>
</nav>

  

posted on   狼来了  阅读(4060)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
阅读排行:
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 易语言 —— 开山篇
· Trae初体验
历史上的今天:
2014-08-08 配置错误定义了重复的“system.web.extensions/scripting/scriptResourceHandler” 解决办法
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示