问题
Routing rules are:
const routes: Routes = [{
path: "",
component: SkeletonComponent,
children: [{
path: "dictionary",
component: DictionaryComponent,
children: [
{
path: ":dict/:code",
component: VersionsComponent
}]
}];
URL looks like:
http://localhost:4200/dictionary/Gender/5
Where Gender
is parameter: :dict
and 5
is parameter :code
.
I tried to get parameters inside component VersionsComponent
:
ngOnInit() {
console.log(this.activateRoute.snapshot.params['dict']);
console.log(this.activateRoute.snapshot.params['code']);
}
I always get undefined
回答1:
The most effective way (works in all scenarios) is to subscribe to Activated Route. It'll work even when you don't switch between components, and only change the parametarised portions of the URL.
this.activatedRoute.params.subscribe(
(params: Params) => {
console.log(params.dict)
}
)
If you don't subscribe to params, the code will only work when the component is loaded initially. After that, you need to leave the component for it to work again. By subscribing, you can load multiple resources without ever leaving the component.
回答2:
As mentioned above go with paramMap. Please refer the stackblitz
ngOnInit() {
this.activatedRoute.paramMap.subscribe((data)=>{
console.log(data.params)
})
}
回答3:
i think Your Routes configuration is wrong, should be like that:
const routes: Routes = [
{
path: '',
component: SkeletonComponent
},
{
path: "dictionary",
component: DictionaryComponent,
children: [{
path: ":dict/:code",
component: VersionsComponent
}]
}
];
and make sure on DictionaryComponent your using <router-outlet>
来源:https://stackoverflow.com/questions/57679513/get-route-parameters-angular