Angular中ActivatedRoute返回空值,跨组件获取路由数据失败求助
解决Angular嵌套路由中获取子路由data的问题
你遇到的核心问题是:HeaderComponent所在的路由层级和NamescanComponent的路由层级不匹配,直接注入的ActivatedRoute只能获取当前组件所在路由节点的data,而你的路由是通过懒加载嵌套的,所以直接订阅activatedRoute.data拿不到子路由的配置数据。
解决方案:遍历激活的路由树获取最深层的路由data
我们可以通过Router监听路由导航完成事件,然后遍历路由树找到当前激活的最底层路由,再从中提取data。具体代码如下:
在header.component.ts中修改逻辑:
import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd, ActivatedRoute } from '@angular/router'; import { filter, map } from 'rxjs/operators'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { constructor(private router: Router, private activatedRoute: ActivatedRoute) { } ngOnInit(): void { this.router.events.pipe( // 只监听导航完成的事件 filter(event => event instanceof NavigationEnd), // 遍历路由树,找到当前激活的最底层路由 map(() => { let currentRoute = this.activatedRoute; while (currentRoute.firstChild) { currentRoute = currentRoute.firstChild; } return currentRoute; }), // 提取路由的data map(route => route.data) ).subscribe(data => { console.log(data.title); // 现在就能拿到'Name Title'啦 }); } }
原理说明
你的路由结构是嵌套的:
- 根路由
''懒加载PagesModule PagesModule内部有namescan路由,配置了data: { title: 'Name Title' }
而HeaderComponent是在根组件或者PagesModule的布局组件中,它的ActivatedRoute对应的是根路由或者PagesModule的父路由节点,并不是namescan的路由节点。通过遍历firstChild,我们能定位到当前激活的最底层路由,从而获取到它的data配置。
内容的提问来源于stack exchange,提问作者Faisal Janjua
相关产品推荐
相关产品推荐

