角路由器-子路由的空数据对象 [英] Angular router - empty data object for child routes

查看:74
本文介绍了角路由器-子路由的空数据对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的角度路由器需要为父级&子路线,但传递数据以区分父路线和子路线.

My angular router needs to use the same component for both the parent & child route, but pass along data to differentiate between the parent and child routes.

当前问题:子路由未注册子路由中的任何数据.

Current issue: the child route does not register any data from the sub-route.

定义关系的路由模块段:

{
        path: 'parent-path/:id',
        component: MyComponent,
        children: [{
          path: 'child-path'
          component: MyComponent,
          data: {MY_DATA_KEY: MY_DATA_VALUE},
        }]
},

在角度分量中:

constructor(
      //...
      private readonly activatedRoute: ActivatedRoute,
      //...
) {}

ngOnInit() {
   this.activatedRoute.data.subscribe(data => {
      console.log('data', data);  // This prints and empty object //

      /* ... do something with data */
   });
}

当前行为:

击中路线'.../parent-path/some-id'

  • 正常预期行为,没有数据

击中路线'.../parent-path/some-id/child-path'

  • 异常行为,数据仍然为空

注意:我还尝试了在父级添加数据,但确实在两条路由上都进行了注册.对Angluar来说相对较新,所以任何帮助都将不胜感激.预先感谢!

Note: I also tried adding data at the parent level, which does get registered at both routes. Relatively new to angluar, so any help would be appreciated. Thanks in advance!

推荐答案

angular的路由器本质上是具有父级和子级的树结构,数据在该树的节点上定义,并且数据对象存在于它们所在的特定节点上被定义.因此,父路由不会在其自己的数据"中看到子路由数据,也不会直接看到其父数据".但是您可以根据需要从激活的路由访问父/子路由

angular's router is essentially a tree structure with parents and children, data is defined at the nodes in that tree, and the data objects exist at the specific nodes where they're defined. so a parent route will not see a child route data in it's own 'data', nor will the child routes see it's parent 'data' directly. But you can access the parent / child routes from the activated route as needed

this.route.parent.data.subscribe(pd => console.log(pd, 'parent data'));

this.route.children.forEach(c => c.data.subscribe(cd => console.log(cd, 'child data'));

这是一个演示行为的堆栈闪电战: https ://stackblitz.com/edit/angular-s4mffg?file = src/app/app.module.ts

here is a stackblitz demonstrating the behavior: https://stackblitz.com/edit/angular-s4mffg?file=src/app/app.module.ts

这篇关于角路由器-子路由的空数据对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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