How do I get access to route parameters in angular 2.0 from components not mapped to a route/router-outlet

1.5k views Asked by At

I've got the following routing

const routes: Routes = [
    { path: 'metadata/:path', component: MetadataDisplayComponent },
    { path: 'data/:path', component: DataDisplayComponent }
]

and here is my AppComponent where the Metadata/Data Display components are injected.

@Component({
    selector: 'my-app',
    template: `
        <tree-view></tree-view>  <!-- a component the displays a tree like hierarchy of the path -->
        <router-outlet></router-outlet>
    `
})

So essentially, I ALWAYS want the tree view to be there doing its thing, regardless of metadata/data state, but I need to initialize it based on a parameter in my routes.

Now, my issue is that my my "tree-view" component needs to access the variable ":path" that I have defined in the 2 routes. When I tried the following (inside my tree-view component)

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
    selector : 'tree-view',
    // etc...
})

export class TreeViewComponent implements OnInit {

    private sub: any;

    contstructor(
        @Inject(ActivatedRoute) private route: ActivatedRoute
    ) {}

    ngOnInit(): void {
        this.sub = this.route.params.subscribe(params => {
            console.log(params['path']);    // this logs "undefined"
        });
    }

    // added this as per the suggestion in the comments
    ngAfterViewInit(): void {
        this.sub = this.route.params.subscribe(params => {
            console.log(params['path']);    // this logs "undefined"
        });
    }

    // etc... 

}

My attempt at accessing the "path" parameter was unsuccessful, it was console.logged as "undefined".

When I tried the exact same ngOnInit inside my MetadataDisplayComponent, I was able to console.log the path no problem.

I'm almost positive that this is because my TreeViewComponent is not associated with one of my routes, and thus has no access to the route variables. It lives next to, but not within the router outlet.

Is there any way I can make this work out? I recognize that I may have planned the layout in a completely stupid way, and am open to suggestions.

1

There are 1 answers

0
Petros Kyriakou On

After several hours searching for same thing this is what worked

inside a service/component outside router-outlet

this.router.events.subscribe(val => {
      if (val instanceof NavigationEnd) {

        let r = this.route;
        while (r.firstChild) {
          r = r.firstChild;
        }
        r.params.subscribe(params => {
          //do stuff with params['yourParam']
          console.log(params);
        });
      }
    });