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

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

问题描述

我的 angular 路由器需要为父级路由器使用相同的组件;子路由,但传递数据以区分父路由和子路由.

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 的 router 本质上是一个有父子的树结构,数据定义在树中的节点上,数据对象存在于它们所在的特定节点上'被定义.所以父路由不会在它自己的数据"中看到子路由数据,子路由也不会直接看到它的父数据".但是您可以根据需要从激活的路由访问父/子路由

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

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

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