Angular路由中包含参数的传递方式

本文介绍了在Angular中如何进行路由跳转并传递参数,包括手动触发的路由跳转时通过`queryParams`传递参数,以及在固定路由中通过查询参数和路径参数的方式传递。在接收端,可以通过`ActivatedRoute`的`queryParamMap`和`paramMap`来获取传递的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、手动触发的路由跳转,并且需要传递含参数

//利用Router.navigate

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


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


//发送方
 this.router.navigate(['/**/**'], { /**/**表示路由地址
      relativeTo: this.route,
      queryParams:{                 //若不需要带参数,queryParams可不带
        user: "username"
      },
 });


//监听路由(接受)方
 this.route.queryParams.subscribe(data => {
    this.user = data.user
 });

2、固定的路由跳转

2.1在查询参数中传递参数

//发送方

直接在路由地址中拼接查询参数,例如
/**/**?id=1&name=2 

const routes: Routes = [{
  path: '',
  children: [{
    path: '',
    redirectTo: 'list',
    pathMatch: 'full'
  },{
    path: '/**/**?id=1&name=2',
    component: NameComponent
  }]
}];




//接收方
利用ActivatedRoute.queryParamMap获取查询参数,例如

 constructor(
    private route: ActivatedRoute){}

this.route.queryParamMap.subscribe(param => {
    this.id = param.get('id');   
});

2.2在路由路径中传递参数

//发送方
在path中利用 : 标注形参
{path: /**/**/:id} => /**/**/1, 例如:
const routes: Routes = [{
  path: '',
  children: [{
    path: '',
    redirectTo: 'list',
    pathMatch: 'full'
  },{
    path: '/**/**/:id',
    component: NameComponent
  }]
}];


//接受方
利用ActivatedRoute.paramMap获取参数,例如:

this.activatedRoute.paramMap.subscribe(params => {
   this.id = params.get('id');
});

参考资料地址:Angular 学习(五):Angular 路由(Route)_Star Zheng的博客-优快云博客_angular路由

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值