how subscribe to first route

366 Views Asked by At

Here is my router:

Routes = [
  { path: 'immeuble', component: ImmeubleComponent ,children:[
    { path: ':id', children: [ { path: 'general',loadChildren: '...'}]
    },
    { path: '', pathMatch:'full', component:AccueilComponent }, //when in url we have /immeuble this is called
  ]},
];

What I try: subscribe to params['id'] inside .ts file of ImmeubleComponent

So my .ts file of ImmeubleComponent looks like:

this.activatedRoute.firstChild.params.subscribe(
      p => {
        console.log(p);
      }
    )

But this subscribe only once when I refresh page, why ? If I go to /immeuble my p=undefined If I type in url /immeuble/2/general, I get well p=2

But this match only when I come on page, when I navigate across my app with router.navigate() My subscribption isn't emitted?

Here I want from ImmeubleComponent subscribe to changement of my id ? How achieve?

Update

add firstChild.params

1

There are 1 best solutions below

3
On BEST ANSWER

I think you would need to subscribe again to the firstChild.params after each navigation probably because you are navigating away from this child route. If you wouldn't use back between these routes, then I assume it would work with firstChild.params.subscribe alone.

This might work for you though

constructor(router:Router, activatedRoute:ActivatedRoute) {
  router.events.filter(e => e instanceof NavigationEnd).subscribe(e => {
    console.log('params', activatedRoute.firstChild.snapshot.params);
  });
}

Plunker example