获取路由参数Angular?
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
最有效的方法(适用于所有场景)是订阅 Activated Route。即使您不在组件之间切换,并且仅更改 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>
路由规则是:
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
最有效的方法(适用于所有场景)是订阅 Activated Route。即使您不在组件之间切换,并且仅更改 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>