从Angular中的另一个组件获取路由器参数 [英] Get router params from another component in Angular

查看:112
本文介绍了从Angular中的另一个组件获取路由器参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular4.我在app.component模板中显示了一些BarComponent(对于几乎所有页面,就像菜单栏一样).我想获得属于"另一个组件而不是BarComponent的子代/子代的路由器参数.
例如,我有一条路线:

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}

我可以使用BarComponent中的Angular方法获得此:id参数吗?
结构就像:

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

推荐答案

我不得不面对这个问题很多次,没有找到angular提供的任何解决方案.

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

因此,我做了一项特殊服务 routeReader ,该服务会接收任何 Router ActivatedRoute ,然后先进行.root.snapshot的使用,然后再进行整体研究children树.

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;
  }

这篇关于从Angular中的另一个组件获取路由器参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆