[英]Use route parameters in Angular 4 with ID is String
如何使用ID為String的路由參數?
{path: 'param/:id', component: MyComponent}
let id = this.route.snapshot.params['id'];
大段引用
如圖所示,使用路由快照獲取id
查詢參數應為您提供一個字符串。 如果要將該字符串隱式轉換為數字,以便可以在用於導航的route參數中使用它,則可以在變量前加上+
:
// (+) converts string 'id' to a number
let id = +this.route.snapshot.params['id'];
然后:
this.router.navigate(['/example', id]);
在文檔https://angular.io/guide/router#snapshot-the-no-observable-alternative中查看獲取查詢參數的示例。
在組件中,您可以使用以下代碼將字符串從數字轉換為數字:
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap
.subscribe((params: ParamMap) => {
let id = +params.get('id'); // This line converts id from string into num
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.