angular路由详解三(路由参数传递)

在路由中传参有3种方法:
1.routerLink
单一参数:在<a routerLink=["/exampledetail",id]>中加routerLink进行跳转,其中/exampledetail是我设置的路由path,id是需要传递的参数。
多个参数:如果要传多个参数,则可以写成routerLink=["/exampledetail",{queryParams:object}] ,queryParams携带多个参数,这个参数的格式可以是自行组织的object,也可以分开多个参数写成routerLink=["/exampledetail",{queryParams:‘id’:‘1’,‘name’:‘yxman’}];。
2.router.navigate
单一参数:this.router.navigate([’/exampledetail’,id]); ,多用在调用方法里
多个参数:this.router.navigate([’/exampledetail’],{queryParams:{‘name’:‘yxman’}});
3.router.navigateByUrl
单一参数:this.router.navigateByUrl(’/exampledetail/id’);
多个参数:this.router.navigateByUrl(’/exampledetail’,{queryParams:{‘name’:‘yxman’}});
传参方传参之后,接收方2种接收方式如下:
1.snapshot
import { ActivateRoute } from ‘@angular/router’;
public data: any;
constructor( public route: ActivateRoute ) { };
ngOnInit(){
this.data = this.route.snapshot.params[‘id’];
};
2.queryParams
import { ActivateRoute } from ‘@angular/router’;
public data: any;
constructor( public activeRoute:ActivateRoute ) { };
ngOnInit(){
this.activeRoute.queryParams.subscribe(params => {
this.data = params[‘name’];
});
};

我们经常用路由传递参数,路由主要有三种方式:

第一种:在查询参数中传递数据

{path:“address/:id”} => address/1 => ActivatedRoute.param[id]

在路由中传递

<a [routerLink] = “[’/address’,1]”>

点击事件传递

this.router.navigate([‘/address’,2])

//在不同等级页面跳转可以用snapshot(快照方式)

this.id = this.routeInfo.snapshot.params[“id”]

//相同组件跳转需要使用subscribe(订阅方式)

this.routeInfo.params.subscribe((params: Params) => this.id = params[“id”] )

第二种:在路由路径中传递参数数据

<a [routerLink] = “[’/address’]” queryParams= “{id:1}”>
this.id = this.routeInfo.snapshot.queryParams[“id”]//拿到路由中的参数

第三种:在路由配置中传递数据
{path:‘home’, component: HomeComponent,data:[{isPush:true}] } => ActivatedRoute.data[0][isPush]
  //同样也是有snapshot和subscribe两种类型
  this.isPush = this.routeInfo.snapshot.data[0][“isPush”]

如果有用请支持,谢谢!

发布了62 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/sirobot/article/details/102495232
今日推荐