angular15 路由传参

一 在模版实现路由跳转功能
1.

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

2.active样式

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

3.传参
1) 通过queryParams

<a routerLink=“./component-a” [queryParams] = “{id:‘1’}”> 跳转a组件
url地址:/component-a?id=1
接收值:

 this.activateRoute.queryParams.subscribe(params=>{
    
    });

2)通过activeParams传参数

  <a [routerLink]="['./component-a' ,{id:'2',aaa:'111'}]" routerLinkActive="active">跳转a组件</a>

接收值:

   this.activateRoute.params.subscribe(params=>{
    
    });  
   this.activateRoute.snapshot.paramMap.get()

3)动态路由传值
这种写法需要在了路由配置模块 且不能再使用上两种方法

{
    
     path: 'component-a/:id', component: ComponentAComponent },
  <a [routerLink]="['./component-a', 3]" routerLinkActive="active" >跳转a组件</a>

接收值:

this.activateRoute.params.subscribe(params=>{
    
    });  this.activateRoute.snapshot.paramMap.get()

二:在ts中实现路由跳转功能
有两个函数实现

  1. navigateByUrl() 基于所提供的 URL 进行导航,必须使用绝对路径。
    两个入参
    url string | UrlTree 一个绝对URL。该函数不会对当前 URL 做任何修改。
    extras NavigationBehaviorOptions 一个包含一组属性的对象,它会修改导航策略。 该函数会忽略 NavigationExtras 中任何可能会改变所提供的 URL 的属性,可选值。默认值为 { skipLocationChange: false }。
    返回值为promise
    可以使用动态路由传值

2.navigate

  this.router.navigate(['component-b']); 以根路由跳转route
    this.router.navigate(['component-b'], {
    
     relativeTo: this.activeRoute }); 以当前路由跳转
    this.router.navigate(['/router-study/component-b']);  固定以根路由跳转
    this.router.navigate(['component-b', '3'], {
    
    
      queryParams: {
    
     aaa: 333, bbb: 3333 },
      relativeTo: this.activeRoute
    });动态传参和查询参数

接收查询参数值: this.activateRoute.queryParams.subscribe(params=>{});
接收动态传参值: this.activateRoute.params.subscribe(params=>{}); 通过this.activateRoute.snapshot.paramMap.get()也能一次性获取传值

猜你喜欢

转载自blog.csdn.net/m0_54944506/article/details/128615374