Get router params from another component in Angula

2019-06-10 01:06发布

问题:

I'm using Angular4. I have some BarComponent that displays in the app.component template (for almost all pages, it's like menu bar). I want to get the router params that "belongs" to another component, not a children/child of the BarComponent.
For example, I have the route:

/some-section-name/:id{here may be sub-routes}

Can I get this :id param using the Angular methods within the BarComponent?
Structure is like:

|- app.component
   |- bar.component
   |- (lazy load) some section
       |- here is the component that has this :id param

回答1:

I had to face this problem many times, didn't find anything already provided by angular to solve it.

So I did a special service routeReader that receive any Router or ActivatedRoute, then take the .root.snapshot of it before exploring the whole children tree.

It may help you.

This is one of the method to read just the main branch, there is not a lot to change to read recursively the whole tree.

getParamsFromTop(route: ActivatedRouteSnapshot) {
    let paramsMap = {};
    let routeCursor = route;
    while (routeCursor) {
      paramsMap = {...paramsMap, ...routeCursor.params};
      routeCursor = routeCursor.children[0];
    }
    return paramsMap;
  }

EDIT 1: Something like this should work if you put root route snapshot.

getParamsRecurse(route: ActivatedRouteSnapshot) {
    let paramsMap = {...route.params};
    for (let i = 0; i < route.children.length; i++) {
      paramsMap = {...paramsMap, ...this.getParamsRecurse(route.children[i])};
    }
    return paramsMap;
  }