angular 路由传参

第一种:
<a [routerLink]="['/product']" [queryParams]="{id: 1}">商品详情</a>
第一种接收参数:
export class ProductComponent implements OnInit { 

  private productId: number;
  constructor(
private routeInfo: ActivatedRoute) {
   }
  ngOnInit() {
    this.productId = this.routeInfo.snapshot.queryParams["id"];
  }
}


<p> product works! </p>
商品Id{{productId}}
第二种:
const routes: Routes = [
  {
    path:'',
    component: HomeComponent
  },
  {
    path: 'product/:id',
    component: ProductComponent
  }
  ,
  {
    path: '**',
    component: Code404Component
  }
];
<a [routerLink]="['/product',1]">商品详情</a>
第二种接收参数:
export class ProductComponent implements OnInit {

  private productId: number;

  constructor(private routeInfo: ActivatedRoute) { }

  ngOnInit() {
    this.productId = this.routeInfo.snapshot.params["id"];
  }

}

参数订阅:

  ngOnInit() {
    this.routeInfo.params.subscribe((params: Params)=> this.productId=params["id"]);
    //this.productId = this.routeInfo.snapshot.params["id"];
  }

参数快照:

  ngOnInit() {
    //this.routeInfo.params.subscribe((params: Params)=> this.productId=params["id"]);
    this.productId = this.routeInfo.snapshot.params["id"];
  }

猜你喜欢

转载自www.cnblogs.com/chenyishi/p/8903110.html