Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ancestor route params in Angular?

I have the following route hierarchy :

const appRoutes:Routes = [
  {
     path: 'article',
     component: ArticleComponent,
     children: [
     {
         path: '',
         component: ArticleListComponent
     },
     {
         path: ':articleId',
         component: ArticleDetailComponent,
          children: [
          {
              path: '',
              component: PageListComponent
          },
          {
              path: ':pageId',
              component: PageComponent
          }]
     }]
 },
  {path: '**', component: DefaultComponent},
];

When I click the Article link , the page is navigated to :

"https://run.plnkr.co/article;listData=foo"

And then I see this :

enter image description here

Now , When I click at Article 2 , the page is navigated to

"https://run.plnkr.co/article;listData=foo/2;detailData=bar"

And then I see this :

enter image description here

Now , when I click at the Page 33 link , the page is navigated to :

"https://run.plnkr.co/article;listData=foo/2;detailData=bar/33;detailData=kro"

And then I see this:

enter image description here

OK

As you can see , at the innermost component ( the single page component) , I set some code to see the current params :

Page  component! {{params | json}}

Which is populated in :

export class PageComponent {
   constructor(private activatedRoute_:ActivatedRoute) {
    activatedRoute_.params
      .subscribe(params => {
        this.params=params;
      });
  }

Question:

Currently the value of params value - is only { "pageId": "33", "detailData": "kro" } which belongs to the final route.

But how can I get the previous routes values ?

I know I can read the querystring but I find it an unconventional way .

The innermost url is :

"https://run.plnkr.co/article;listData=foo/2;detailData=bar/33;detailData=kro"

So basically I'm asking how can I extract all the parameters from prev routes.

( I mean what are the values for articleId , listData , detailsData (the first one) )?

PLNKR

like image 942
Royi Namir Avatar asked Sep 08 '25 03:09

Royi Namir


2 Answers

You can get all parents params using snapshot. In detail component:

let node = activatedRoute_.snapshot;
while(node) {
  console.log('component', node.component.name, ', params:', node.params);
  node = node.parent;
}

 component ArticleDetailComponent , 
            params: Object {articleId: "1", detailData: "bar"}
 component ArticleComponent , params: Object {listData: "foo"}
 component RootComponent , params: Object {}
like image 100
Julia Passynkova Avatar answered Sep 09 '25 15:09

Julia Passynkova


You should be sending the listData value along with the object.Modify this to your app/article-list.component.ts Component

<a [routerLink]="[articleId, {listData:'foo',detailData: 'bar'}]">

LIVE DEMO

like image 31
Aravind Avatar answered Sep 09 '25 17:09

Aravind