Search code examples
angularangular-lifecycle-hooks

Get the url param from nested component


I develop a MEAN stack application and for the Front-End I use Angular. In angular, I use a navbar and a sidenav bar which are the framework of my layout. Then the routes are displayed in the mat-sidenav-content -> ng-content here:

FRAMEWORK COMPONENT HTML

  <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    MY CONTENT NAVBAR
  </nav>

  <mat-sidenav-container class="sidenav-container">
    <mat-sidenav>
    MY CONTENT SIDENAV
    </mat-sidenav>

    <mat-sidenav-content style="background-color: #ecf0f1">
      <ng-content></ng-content>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>

The others components are displayed properly. However, I would like to access the url from the framework component like this:

       import { ActivatedRoute } from "@angular/router";
[...]
        constructor(private route: ActivatedRoute) {}
[...]
        this.route.snapshot.params["id"]

It doesn't work because it's undefined whereas if I do it in the other components it works. I think it is because the FRAMEWORK component is not defined in the router therefore there is not URL for this component.

I tried to use a sharing data service. Like this I set the id value in the other component and the framework component can use it. But it doesn't work because Framework component is loaded before the other component.


Solution

  • You may subscribe to route change events in the component that gets loaded. And then update the id of service from there. So that main nav component will receive the updated id after it is emitted from service.

    And you should make your service singleton, so that each component share the same Service instance. To do this, you should provide your service at the module level.

    shared service

    class Service {
       emitData(id){
          this.sub.next(id)
       }
    }
    

    Nav comp

    class NavComponent {
           ngOnInit(){
              this.service.sub.subscribe(id => console.log(id));
           }
    }
    

    Routed comp

    class NavComponent {
           ngOnInit(){
            this.router.events.subscribe((event) =>
            {
              if(event instanceOf NavigationEnd) { 
                 // fetch id from url and call service method to emit data
                  this.service.emitData(id);
              }
           });
     }