Search code examples
angularangular2-routingresolver

Angular 4 - Route Resolve For Nested Component?


I have the following structure:

Parent Component
 |__Nested Component 1
 |__Nested Component 2
     |__Nested Component 3 

I am trying to resolve some data into Nested Component 3 - the only component here that has a route here is Parent Component. Is there some way to get the resolve data in Nested Component 3 without:

A. Using @Input - this is dirty going down a chain of three components.
B. Using some service - I realize I can save the data to some service and retrieve it in Nested Component 3 - maybe this is the way to go, but I am looking for other options. Though this might be the only real way.

So, what's the best approach here. Iirc in Angular 1, all child components could get resolved data, but that doesn't seem to be the case here.


Solution

  • You can get the route parameters of parent routes like this:

    ngOnInit() {
      const pathFromRoot = this.route.pathFromRoot;
      let paramsSub = Observable.merge(...pathFromRoot.map(p => p.params));
      paramsSub.subscribe(params => {
        //emits the params map for each parent route.
        console.log(params);
      });
    }
    

    Just be aware that you're going to get a map of route params for each route in the tree. So in your case that subscribe callback will be fired twice.

    You can't really combine them all into one mashed up object because the route params subscription never "completes".