关于angular2路由传参
在开发一个网站中遇到需要在路由传参的需求,一个示例列表组件,其中每个示例项点击进入均可加载该示例详情页。
在路由中传参有3种方法:
1.routerLink
单一参数:在<a routerLink=["/exampledetail",id]></a>中加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"
];
});
};
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 浅谈程序优化
- 下一篇: Unity3D代码及效率优化总结