angular中的路由跳转及路由传参方法整理

本文介绍Angular中的两种路由跳转方式:通过模板链接和方法进行跳转。此外还详细解释了四种路由传参的方法,包括通过模板跳转时添加查询参数或使用动态路由,以及通过方法跳转时如何携带参数。

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

路由跳转方式 总的大概分为两种

通过模板链接进行跳转

两种写法

    <a  routerLink="./component-a">跳转a组件</a>
    <a  [routerLink]="['./component-a']" >跳转a组件</a>

定义路由

{path: 'component-a', component: ComponentAComponent}

定义路由出口

<router-outlet></router-outlet>

通过方法进行跳转

需要注入两个服务
Router 一个提供导航和操纵 URL 能力的 NgModule。
ActivatedRoute: angular中ActivatedRoute
Router.navigate返回值是一个promise 值为boolean类型,是否跳转成功

 constructor(public router:Router,public activeRoute:ActivatedRoute) { }
 toComponentB(){
  this.router.navigate(['component-b'] , {relativeTo: this.activeRoute}).then(r => console.log(r))
}

跳转按钮

<button nz-button nzType="primary" (click)="toComponentB()">跳转b组件</button>

定义路由

{path: 'component-b', component: ComponentBComponent}

路由传参

每种跳转方式都有两种,共计有四种路由传参方式

通过模板跳转的两种路由传参方式

第一种:
在路由上添加查询参数,定义路由未进行修改

  {path: 'component-a', component: ComponentAComponent}
  <a  routerLink="./component-a" [queryParams]="{id:'1'}">跳转a组件</a>
页面地址://localhost:4200/router-study/component-a?id=1
<a [routerLink]="['./component-a' ,{id:'2'}]" routerLinkActive="active">跳转a组件</a>
页面地址 http://localhost:4200/router-study/component-a;id=2

两种写法的接受方式不同
接收:

 id: string = ''

constructor(public activeRoute: ActivatedRoute) {
}

ngOnInit(): void {
  this.activeRoute.queryParams.subscribe(res => {
      this.id = res['id']
    }
  )
     this.activeRoute.params.subscribe(res => {
      this.id = res?.id
    })
}

第二种:
动态路由,定义路由进行修改

  {path: 'component-a/:id', component: ComponentAComponent}
 <a [routerLink]="['./component-a' ,'2']" routerLinkActive="active">跳转a组件</a>
页面地址 http://localhost:4200/router-study/component-a/2

接收传参方式:

this.activeRoute.params.subscribe(res => {
     this.id = res?.id
   })

通过方法进行跳转传参

第一种:在路由上添加查询参数

this.router.navigate(['component-b',{id:'3'}] , {relativeTo: this.activeRoute}).then(r => console.log(r))
http://localhost:4200/router-study/component-b;id=3

接收:两种方式都可以获得到参数

this.activateRoute.params.subscribe(res => {
  this.id = res['id']
})
if (this.activateRoute.snapshot.paramMap.get('id')) {
  this.id = this.activateRoute.snapshot.paramMap.get('id')
}

第二种 动态路由
定义路由进行修改

 {path: 'component-b/:id', component: ComponentBComponent}
  this.router.navigate(['component-b','3'] , {relativeTo: this.activeRoute}).then(r => console.log(r))
http://localhost:4200/router-study/component-b/3

接收:两种方式都可以获得到参数

this.activateRoute.params.subscribe(res => {
   this.id = res['id']
 })
 if (this.activateRoute.snapshot.paramMap.get('id')) {
   this.id = this.activateRoute.snapshot.paramMap.get('id')
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值