路由傳參數(shù)
1、在查詢時(shí)傳參數(shù)
模板中示例:
<a [routerLink]="['/product']" [queryParams]="{id:1}">商品詳情</a>
在product組件中示例:
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;//定義接收的ID變量
constructor(private routeInfo:ActivatedRoute) { }
ngOnInit() {
/*通過(guò) queryParams 方法取得參數(shù)*/
this.productId = this.routeInfo.snapshot.queryParams['id'];
}
}
在product模板中示例:
<p>
這是一個(gè)商品組件
</p>
<p>
查詢參數(shù)傳遞過(guò)來(lái)的組件ID:{{productId}}
</p>
2也切、在路由路徑中傳遞參數(shù)
2.1 修改數(shù)由配置app-routing.module.ts中的path屬性,使其可以攜帶參數(shù)
{path:'product/:id',component:ProductComponent},
2.2 修改數(shù)由鏈接 routeLink的參數(shù)室囊,使其可以傳遞參數(shù)
<a [routerLink]="['/product',1]">商品詳情</a>
2.3 所ActivatedRoute中的queryParams ['id']改為params['id']
this.productId = this.routeInfo.snapshot.params['id'];
2.4 注意: activatedRouter 構(gòu)造之后在ngOnInit (在組件第一次呈現(xiàn)的時(shí)候只被調(diào)用一次)生命周期中調(diào)用的snapshot是參數(shù)快照忍啸;
還有一種得參數(shù)訂閱择份,如果在組件路由到自身的情況下胡桨,必須使用參數(shù)訂閱(subscribe)官帘,才能取到動(dòng)態(tài)的參數(shù);
app.component.html中示例
<a [routerLink]="['/']">主頁(yè)</a>
<a [routerLink]="['/product',1]">商品詳情</a>
<input type="button" value="商品詳情" (click)="toProductDetails()">
<!-- / 開(kāi)頭的叫根路由 ./ 開(kāi)頭的是子路由 -->
<!-- routerLink [] 里面可以傳參數(shù) -->
<!-- (click) 括號(hào)里面的是Angular的事件綁定用法 綁定到 組件控制器中的toProductDetails方法 -->
<!-- 路由暫位符號(hào) -->
<router-outlet></router-outlet>
在product組件中示例
ngOnInit() {
/* 通過(guò)參數(shù)訂閱取得數(shù)據(jù) */
this.routeInfo.params.subscribe((param:Params)=>this.productId = param['id']);
/*通過(guò) queryParams 方法取得參數(shù)快照*/
// this.productId = this.routeInfo.snapshot.params['id'];
}
在app.component組件中的控制器toProductDetails中示例:
toProductDetails() {
/* 通過(guò)控制器的navigate方法來(lái)路由到product組件上面 */
this.router.navigate(['/product',2]);
}
3昧谊、在路由配置中傳遞參數(shù)