angular路由传参方式主要有3种,说明:
第一种:在查询参数中传递数据
/product?id=1&name=2 => ActivatedRoute.queryParams[id]
第二种:在路由路径中传递数据
{path: /product/:id } =>/product/1 => ActivatedRoute.params[id]
第三种:在路由配置中传递数据
{path: /product, component: ProductComponent, data:[{ isProd:true }]} => ActivatedRoute.data[0][isProd]
一、在查询参数中传递数据
1、在app.component.html中
<a [routerLink] = "['/product']" [queryParams] = "{id:1}">产品ID</a>
2、在product.component.ts中接收参数
import {ActivatedRoute} from '@angular/router'; export class ProductComponent implements OnInit { private productId: number; constructor( private routerInfo: ActivatedRoute ){} ngOnInit() { this.productId = this.routerInfo.snapshot.queryparams["id"] ; } }
3、在product.component.html中
<p>产品Id是:{{productId}}</p>
二、在路由路径中传递数据
1、在app-routing.module.ts
{path:'product/:id', component: ProductComponent}
2、在app.component.html中
<a [routerLink]="['/product',1]">商品详情</a>
3、在product.component.ts中
import {ActivatedRoute} from '@angular/router'; export class ProductComponent implements OnInit { private productId: number constructor(private routerInfo: ActivatedRoute){} ngOnInit() { this.productId = this.routerInfo.snapshot.params["id"]; } }