问题
I have this in my route.ts
path: 'profile/:id',
component: ProfileComponent,
canActivate: [SiteRouteGuard],
children: [
{
path: 'albums',
component: AlbumsComponent,
canActivate: [SiteRouteGuard]
},
...
]
Now in my profile.ts I got this
localhost:4200/profile/45666
and when I route to album.ts that is chlidren of my profile.ts
localhost:4200/profile/45666/albums
Now I'm in my album.ts how can I get the id 45666?
I tried to use ActivatedRoute:
console.log(this._route.snapshot.params.id) >> undefined
回答1:
You can use the ActivatedRoute
class from angular/router
import { ActivatedRoute, Router } from "@angular/router"
public activatedRoute: ActivatedRoute
this.activatedRoute.parent.params // return observable
if you want the static value, then ask for
this.activatedRoute.parent.snapshot.params // return static values
By using the attribute parent, you can access to all the parameters and queries from the parent component
回答2:
Since angular 5.2.x
there is another way to access parent params.
All you have to do is set config option paramsInheritanceStrategy to 'always'
like this:
RouterModule.forRoot(routes, {
paramsInheritanceStrategy: 'always'
})
With this config, you will have access to all ancestor routes params via prototypal inheritance, so you can get it directly from activated route:
this.activatedRoute.snapshot.params
回答3:
You need to import ActivatedRoute from @angular/router:
import { ActivatedRoute } from "@angular/router";
Then in your constructor of AlbumsComponent you can grab that :id parameter like this:
let id = this.activatedRoute.parent.snapshot.params["id"]
Hope it helps!
回答4:
If you are using activatedRoute you can get id in ngOnInit() method. like
this.activatedRoute.params.subscribe((params: Params) => {
var id = params['id'];
});
回答5:
Do it like this
import { ActivatedRoute } from "@angular/router";
let idparam = this.activatedRoute.parent.snapshot.params["idparam"]
来源:https://stackoverflow.com/questions/49349498/how-to-get-params-url-parent-id-from-children