(五)、Angular4.0 路由传递参数

一、在查询参数中传递参数

  • 修改app.component.html中的商品详情页a标签
商品详情页

  • 修改product.component.ts接收传递过来的参数
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;

  constructor(private routeInfo: ActivatedRoute) { }

  ngOnInit() {
    this.productId = this.routeInfo.snapshot.queryParams['id'];
  }

}
  • 修改product.component.html,新增

    商品ID : {{productId}}

  • 访问localhost:4200点击商品详情连接测试


二、在路由路径(url)中传递参数

  • 修改路由配置中的path属性,使其可以传递参数   app-routing.module.ts
{path: 'product/:id', component: ProductComponent}
  • 修改app.component.html 商品详情页链接
商品详情页
  • 修改product.component.ts 接收参数的配置 queryParams改为params
  ngOnInit() {
    this.productId = this.routeInfo.snapshot.params['id'];
  }

  • 访问localhost:4200 测试


三、在路由配置中传递参数

  • 修改app.component.ts中的toProductDetails()
  toProductDetails() {
    this.router.navigate(['/product', 2]);
  }
  • 把product.component.ts中ngOnInit()从参数快照改为参数订阅
  ngOnInit() {
    this.routeInfo.params.subscribe((params: Params) => this.productId = params['id']);
  }

四、访问localhost:4200 点击商品详情链接和按钮都可以分别获取到数据

你可能感兴趣的:(Angular,4.0)