angularobservableangular-servicesangular-routerangular-router-params

How to subscribe to child route params and use result to run another service?


I'm trying to have the following scenario working; I have a screen, lets call it AdminComponent, which has two sidebars and a router-outlet which displays the selected item route.

<div class="console container">
    <div class="sidebar-left"></div>
    <div class="sidebar-right"></div>
    <div class="outlet-container">
        <router-outlet></router-outlet>
    </div>
</div>

The idea I'm trying to accomplish is the following:

On left-sidebar I render multiple links which change the route to /admin/:id; I use a simple get service to fetch the data I need for each item to render the links.

On right-sidebar I'm trying to subscribe to the route parameters so that when the value changes, I can also run a different service fetch the data for the specific :id which will contain an array of action-items for the item selected on the left-sidebar.

The last part is what I'm having troubles with since I don't see the subscription to the parameters working; I have tried using:

this.route.firstChild.paramMap.subscribe()

But this throws an error when I'm on the parent route admin/, it only works if I navigate directly to admin/1 for example. I need to subscribe to the route change so I can render the items on the right sidebar but I don't really know how to approach it at this point.

Hope it is clear enough, any other details that might help I can provide them.


Solution

  • What you want to do is listen for any navigation and then get the queryParams like so

    import { Router, ActivatedRoute } from '@angular/router';
    
    // ... 
    
    constructor( 
      public activatedRoute: ActivatedRoute, 
      public router: Router
    ) {}
    
    // ...
    
    ngOnInit() {
       this.listenForRouteChange();
    }
    
    listenForRouteChange() {
       this.router.events
         .pipe(filter(x => x instanceof NavigationEnd))
         .subscribe(result => {
           // you could do two things here, if you know that you are only ever going
           // to have the single param you can do this
           let url = result.urlAfterRedirects.split('/');
           let params = url[url.length - 1]; 
    
           // or if you want to be more precise call this function
           this.getRouteParams();
         });
    }
    
    getRouteParams() {
       this.activatedRoute.queryParams
         .subscribe(result => {
           let id = result.id;
         });
    }