小白入门angular-cli的第一次旅程(学习目标 1.路由的基础知识 在路由时传递数据)
更新:HHH   时间:2023-1-7


第一篇文里学习了在路由的基础知识,了解了路由5个对象Routes,RouterLink,RouterOutlet,Router的写法,这篇文里来学习如何在路由时传递数据, 还有如何使用ActivatedRoute的使用方法 

    传递数据方式主要有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]


            一.在查询参数中传递数据

                步一:在app.component.html中

                           <a [routerLink] = "['/product']"  [queryParams] = "{id:1}">产品ID</a>

                 步二:在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"] ;

                                 }

                            }

                    步三:在product.component.html中

                               <p>产品Id是:{{productId}}</p>

            二.在路由路径中传递数据

                   步一:在app-routing.module.ts

                              {  path : ' product / : id  ',  component : ProductComponent  }      

                    步二:在app.component.html中

                                <a [routerLink] = "['/product',1]">商品详情</a>  

                    步三:在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"]

                                          }

                                  }

 

    

    


返回web开发教程...