- 在路由时传递数据
/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中传递参数
- 修改路由配置中的地址
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"];
}
}