Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get params url parent id from children

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
like image 436
Roula Halabi Avatar asked Mar 18 '18 15:03

Roula Halabi


2 Answers

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

like image 196
Krzysztof Grzybek Avatar answered Sep 22 '22 12:09

Krzysztof Grzybek


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

like image 44
Ricardo Avatar answered Sep 21 '22 12:09

Ricardo