我想通過使用routerLink的URL傳遞一個值。並在另一頁上讀取該值。 像我有產品清單。在選擇第一條記錄時,該記錄的標識傳遞到產品詳細信息頁面。讀完productId後,我想顯示該產品的詳細信息。如何在Angular 2中通過routerLink獲取參數?
那麼如何傳遞並獲取參數?
我想通過使用routerLink的URL傳遞一個值。並在另一頁上讀取該值。 像我有產品清單。在選擇第一條記錄時,該記錄的標識傳遞到產品詳細信息頁面。讀完productId後,我想顯示該產品的詳細信息。如何在Angular 2中通過routerLink獲取參數?
那麼如何傳遞並獲取參數?
我是假設你有這樣的代碼:
{ path: 'product/:id', component: ProductDetailComponent }
in ProductL北京時間模板
<a [routerLink]="['/product', id]">Home</a>
或
<a [routerLink]="['/product', 5]">Home</a>
其中id
是一個變量,也許你在一個循環中得到它。
在ProductDetailComponent:
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params
// (+) converts string 'id' to a number
.switchMap((params: Params) => this.yourProductService.getProductById(+params['id']))
.subscribe((product) => this.product = product);
}
在您的a
標記上使用routerLink
來標記url。
[routerLink]="['yourRouteHere', {'paramKey': paramValue}]
爲了得到它,你需要使用ActivatedRoute
服務。將它注入組件並使用它的訂閱方法。這裏我route
是注射服務
this.route.params.subscribe(params => {
const id = Number.parseInt(params['paramKey']);
}
如果你想從路段使用.params
,如果從查詢字符串想別的參數,使用.queryParams
1. 假設您的網址是HTP://abc.com/xyz和期望的結果是 HTP: //abc.com/zyx/users?id=1然後使用以下代碼
<a [routerLink]="['user']" [queryParams]="{id: 1}" </a>
2 .suppose網址是HTP://abc.com/xyz和您的期望的結果是HTP://abc.com/users ID = 1下面的代碼
使用
<a [routerLink]="['/user']" [queryParams]="{id: 1}" </a>
thanx,但它給我錯誤。 – MohammedAshrafali
但是'[routerLink] =「['yourRouteHere',{'paramKey':{'key':'value'}}]''' – Toolkit