Home > Software design >  ActivatedRoute subscribe not triggering in child component
ActivatedRoute subscribe not triggering in child component

Time:12-08

let's consider the following routing :

 path: 'requests/:id', component: PublicationsRequestDetailComponent, resolve: { request: PublicationsRequestDetailResolverService },
            runGuardsAndResolvers: 'always',
            children: [
                 {
                    path: 'summary', component: PublicationsRequestSummaryComponent
                },

If I do this in the PublicationsRequestDetailComponent :

 ngOnInit(): void {
   this._route.params.subscribe(m => {
  console.log(m);
 });
}

I can read the id parameter passed in the route (m = {id: 'some value'})

however, the same code inside the PublicationsRequestSummaryComponent gives me m = {}

So in the child component, the route params is an empty object.

Why is that ? How can detect route changes from my child component ?

CodePudding user response:

A) You should put an Id in the child path as well, shouldn't?

...
children: [
                 {
                    path: 'summary/:id', 
                    component: PublicationsRequestSummaryComponent
                },
...

B) Besides, I guess there is another way to get the rute id parameter, in this way:

  ngOnInit(): void {
    console.log(this.activatedRoute.snapshot.paramMap.get('id'));
  }

You could test both solutions, first the A), then B), and finally A B together.

CodePudding user response:

ok, the fix was to use route.parent

 this._route.parent.params.subscribe(m => {
    console.log(m);
 });
  • Related