[英]Get route parameters Angular?
路由規則是:
const routes: Routes = [{
path: "",
component: SkeletonComponent,
children: [{
path: "dictionary",
component: DictionaryComponent,
children: [
{
path: ":dict/:code",
component: VersionsComponent
}]
}];
URL 看起來像:
http://localhost:4200/dictionary/Gender/5
其中Gender
是參數: :dict
, 5
是參數:code
。
我試圖在組件VersionsComponent
中獲取參數:
ngOnInit() {
console.log(this.activateRoute.snapshot.params['dict']);
console.log(this.activateRoute.snapshot.params['code']);
}
我總是undefined
最有效的方法(在所有情況下均有效)是訂閱“激活的路由”。 即使您無需在組件之間切換,也只需更改URL的參數化部分,它便會起作用。
this.activatedRoute.params.subscribe(
(params: Params) => {
console.log(params.dict)
}
)
如果您不訂閱參數,則代碼僅在最初加載組件時有效。 之后,您需要離開該組件以使其再次工作。 通過訂閱,您可以加載多個資源,而無需離開組件。
如上所述,請使用paramMap。 請參考stackblitz
ngOnInit() {
this.activatedRoute.paramMap.subscribe((data)=>{
console.log(data.params)
})
}
我認為您的路線配置錯誤,應該是這樣的:
const routes: Routes = [
{
path: '',
component: SkeletonComponent
},
{
path: "dictionary",
component: DictionaryComponent,
children: [{
path: ":dict/:code",
component: VersionsComponent
}]
}
];
並確保在DictionaryComponent上使用<router-outlet>
根據 Angular 文檔,使用“訂閱”方法的其他答案部分正確,但您仍然收到錯誤的原因是它們缺少“get()”部分:
https://angular.io/api/router/ParamMap
嘗試這個:
import { Router,ActivatedRoute } from '@angular/router'; myVar ngOnInit(): void { this._Activatedroute.paramMap.subscribe((data) => { this.myVar = data.get('NameOfVariable') // Put the name of whatever variable you're trying to get here }) console.log(this.myVar) }
似乎您已經收到有關如何從父級傳遞數據的幫助,但只是為了完善答案,這就是我通常這樣做的方式:
<button [routerLink]="['/myLink',dataVar]"> Click Here </button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.