angular路由传参

  • 在路由时传递数据
/product?id=1&name=2 '数据的接收' '在路由的目标组件中,可以通过以下方式获得数据'

 ActivatedRoute.queryParams[id] AcitvatedRoute.queryParams[name]
  • 在路由的路径中传递数据
'定义路由路径时,指定参数的名字'
 {path:/product/:id} 
'在实际的路径中携带这个参数'
 /product/1 
'在路由的目标组件中使用以下方式拿到参数'
 ActivatedRoute.params[id]

 

  • 在路由的配置中传递数据
'以下内容是路由的配置' 
{path:/product,component:ProductComponent,data:[{isProd;true}]} 
'在路由的目标组件中,通过以下语法拿到数据' 
ActivatedRoute.data[0][isProd]

 

实例

  • 在查询参数中传递数据

  • 在去目标路由组件中获得这个数据
export class ProductComponent implements OnInit { 
    '定义接收数据的变量' 
    private productId: number;
     '在构造函数中引入这个类型'
     constructor(private routeInfo: ActivatedRoute) { }
     ngOnInit() { '接收传递过来的参数' this.productId = this.routeInfo.snapshot.queryParams["id"]; } }

 

  • 在URL中传递参数

 

  1. 修改路由配置中的地址
const routes: Routes = [
 { 
    path: '', component: HomeComponent }, 
    '地址携带参数'
     {path: 'product/:id', component: ProductComponent}
 ];

2、给参数赋值

<a [routerLink]="['/']">主页</a> 
'product后面的1即为参数id对应的值' 
<a [routerLink]="['/product',1]" >商品详情</a>

3、读取参数的值

export class ProductComponent implements OnInit {
 '定义接收数据的变量' 
  private productId: number; 
  '在构造函数中引入这个类型' 
  constructor(private routeInfo: ActivatedRoute) { 
} 
  ngOnInit() { 
 '接收传递过来的参数'
  this.productId = this.routeInfo.snapshot.params["id"]; 
 } 
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LLLDa_&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值