Angular路由——在路由時候傳遞數據
有3種方式
1、在查詢參數中傳遞數據
2、在路由路徑中傳遞數據
定義路由路徑時就要指定參數名字,在實際路徑中攜帶參數。
3、在路由配置中傳遞數據
一、在查詢參數中傳遞數據
第一步:修改模版中商品詳情鏈接,帶一個指令queryParams
<a [routerLink]="['/product']" [queryParams]="{id:1}">商品詳情</a>
效果:點擊鏈接會傳一個商品id爲1的參數過去。
第二步:在商品詳情組件中接收參數
用ActivatedRoute接收id並賦值給productId顯示在模版中。
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"];
}
}
修改模版顯示
<p>
這裏是商品信息組件
</p>
<p>
商品id是{{productId}}
</p>
二、 在路由路徑中傳遞數據
第一步:修改路由path屬性使其可以攜帶數據
{ path: 'product/:id', component: ProductComponent },
第二步:修改路由鏈接的參數來傳遞數據
傳一個2過去。
<a [routerLink]="['/product',2]">商品詳情</a>
效果:
第三步,商品詳情信息組件,從url中取id
this.productId = this.routeInfo.snapshot.params["id"];
三、參數快照和參數訂閱
1、參數快照問題
參數快照就是從snapshot中獲取參數。
this.productId = this.routeInfo.snapshot.params["id"];
修改:
商品詳情按鈕的響應函數,傳遞一個3過去。
toProductDetails(){
this.router.navigate(['/product',3]);
}
問題:
先點主頁,再點商品詳情鏈接正確跳轉到商品詳情組件,再點商品詳情按鈕,問題來來,url中id變爲來3,內容顯示中id沒有變還是2。
原因:
從home組件路由到component組件,商品詳情組件會被創建,它的constructor(),ngOnInit()會被調用一次。
但是從商品詳情組件直接路由到商品詳情,由於商品詳情組件在點擊商品詳情按鈕時已經被創建了,它不會再次被創建,ngOnInit()方法不會再次被創建。所以productId依然保存着第一次被創建時候的值。
解決辦法:參數訂閱。
2、參數訂閱
rxjs的subscribe方法。
ngOnInit() {
this.routeInfo.params.subscribe((params: Params)=> this.productId=params["id"]);
}
問題得以解決。
獲取路由參數時候:
如果確定一個組件不會從自身路由到自身,可以通過參數快照方式獲取參數。
不確定,則用參數訂閱方式獲取。