核心提示:第一步:1.修改app-routing.module.ts路由配置关于product的path属性,使其携带id参数const routes: Routes = [{path: , component...
第一步:
1.修改app-routing.module.ts路由配置关于product的path属性,使其携带id参数
const routes: Routes = [ {path: '', component:HomeComponent}, //具体路由放在最前面 {path: 'product:/id', component:ProductComponent}, //路由通过URL传数据,--1.第一步修改了路由配置的path属性,时期携带id参数 {path:'**',component:Code404Component}, //通配符路由放在最后面 ];
第二步:
在appcomponent.html中 routerlink是一个数组,我们可以增加元素,这里要和app-routing.module.ts里面路由配置path属性对应,第一个元素是固定的product,第二个是我们的id参数
商品详情
可以看出来我们的URL路径已经变成了/product/1了
第三步:
更改商品信息组件,从URL中取传递过来的参数值,与查询参数传递类似,只是将queryparams改为params.
import { Component, OnInit } from "@angular/core"; import { ActivatedRoute } from "@angular/router"; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { private productId:number; //定义一个变量来接收路由传递过来的productId constructor(private routeInfo: ActivatedRoute) { } //从查询参数里面去取改为从URL中去取,将原来的queryparams改为params ngOnInit() { this.productId=this.routeInfo.snapshot.params["id"]; } }