如何获取所有路线参数/数据 [英] How to get all route params/data

查看:92
本文介绍了如何获取所有路线参数/数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出路​​由配置

{
   path: '/root/:rootId',
   children: [{
       path: '/child1/:child1Id',
       children: [{
           path: '/child2/:child2Id
           component: TestComponent
       }]
   }]
}

在TestComponent中,我如何轻松获取所有路由参数.我想知道是否有比这更简单的方法

In TestComponent how can I easily get all route params. I'm wondering if there is an easier way than

let rootId = route.parent.parent.snapshot.params;
let child1Id = route.parent.snapshot.params;
let child2Id = route.snapshot.params;

这似乎是多余的,特别是如果我正在观察可观察到的路由参数,而不是通过路由快照访问该参数.此方法似乎也很脆弱,因为如果我移动任何路线/参数,它都会中断.我习惯于使用角度ui路由器,在该ui路由器中,为单个对象$ stateParams提供了易于访问的所有参数数据.我对从路由树中的单个节点访问的路由解析数据也有同样的担忧.任何帮助将非常感激.预先感谢

This seems overly redundant especially if I'm watching the route params observable instead of access the param through the route snapshot. This method also seems fragile since it would break If I moved any any of the routes/params around. Im used to angular ui-router where a single object $stateParams was supplied with all param data easily accessible. I have these same concerns with route resolved data along being accessed from a single node in the route tree. Any help would be much appreciated. Thanks in advance

推荐答案

从Angular 5.2开始,您可以进行Router配置以将所有参数继承到子状态.如果对血腥细节感兴趣,请参见此提交,但这是它对我的工作方式:

As of Angular 5.2, you can do Router configuration to inherit all params to child states. See this commit if interested in the gory details, but here's how it's working for me:

在调用RouterModule.forRoot()的任何地方,都包括一个配置对象,该配置对象的继承策略设置为always(默认值为emptyOnly):

Wherever you have your call to RouterModule.forRoot(), include a configuration object with the inheritance strategy set to always (default is emptyOnly):

import {RouterModule, ExtraOptions} from "@angular/router";

export const routingConfiguration: ExtraOptions = {
  paramsInheritanceStrategy: 'always'
};

export const Routing = RouterModule.forRoot(routes, routingConfiguration);

现在,当您在子组件中查看ActivatedRoute时,祖先的参数会出现在此处(例如activatedRoute.params),而不是像activatedRoute.parent.parent.parent.params这样的凌乱的东西.您可以直接访问该值(例如activatedRoute.params.value.userId)或通过activatedRoute.params.subscribe(...)订阅.

Now when you're in a child component looking at a ActivatedRoute, ancestors' params appear there (e.g. activatedRoute.params) rather than something messy like activatedRoute.parent.parent.parent.params. You could access the value directly (e.g. activatedRoute.params.value.userId) or subscribe via activatedRoute.params.subscribe(...).

这篇关于如何获取所有路线参数/数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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