Angular服务中重定向后无法获取初始路由数据的问题
Angular服务无法获取首次重定向后的路由数据(动态面包屑场景)
我在基于当前路由创建动态面包屑数据时遇到问题:Angular服务中无法获取重定向后的首个路由数据,仅将代码移至组件内时才能正常获取。
相关代码
路由配置(app.routing)
export const routes: Route[] = [ { path: '', canActivate: [AuthGuard], component: LayoutMainComponent, children: [ { path: 'first', children: [ { path: 'second', loadComponent: () => import('....component'), }, { path: '', redirectTo: 'first', pathMatch: 'prefix', }, ], }, { path: '', redirectTo: 'first/second', pathMatch: 'prefix', }, ]
面包屑服务代码
当前的Observable在用户切换路由时正常工作,但首次加载时无法获取重定向后的路由:
// 该Observable在用户切换路由时正常工作,但首次加载时无效 breadcrumbMenuItems$: Observable<MenuItem[]> = this.router.events.pipe( filter((event): event is NavigationEnd => event instanceof NavigationEnd), map((event: NavigationEnd) => { const url = event.urlAfterRedirects || this.router.url; return this.generateBreadcrumbs(url); }), startWith(this._fetchInitialBreadcrumbs()), distinctUntilChanged(), catchError((error: any) => { console.error(this.errorMessage, error); return of([]); }), );
尝试获取重定向路由的代码
我尝试了多种方式获取目标路由/first/second,但结果要么是重定向前的空路径/,要么是undefined:
constructor( private router: Router, private activatedRoute: ActivatedRoute, private readonly location: Location ) { console.log('========= ROUTER ==========='); console.log('ROUTER::', this.router); console.log( 'ROUTER: routerState.snapshot-URL:', this.router.routerState.snapshot.url ); console.log('this.router.url:', this.router.url); console.log(' =============== ACTIVATED ROUTE ==============='); console.log('activatedRoute.pathFromRoot:', this.activatedRoute.pathFromRoot ); console.log( 'activatedRoute.snapshot.url:', this.activatedRoute.snapshot ); this.activatedRoute.paramMap.subscribe((params) => { console.log( 'params:', params ); console.log( 'params.next:', params['next'] ); }); console.log( 'routeConfig', this.activatedRoute.routeConfig?.path?.split('?')[0] ); console.log(' ========== Angular LOCATION ==========='); console.log('location:: ', this.location.path()); console.log(' =============== window ==============='); console.log('windowURL:' , window.location.href); console.log('windowPath:' , window.location.pathname); }
奇怪现象
直接打印this.router.routerState.snapshot.url返回/,但展开console.log('ROUTER::', this.router);的日志时,里面的routerState.snapshot.url却是我需要的/first/second。
补充说明
我不想在服务内手动订阅,因为采用Rxjs声明式响应式方案,会将breadcrumbMenuItems$与其他布局Observable组合成layout vm$,仅在一处使用async管道订阅。
内容的提问来源于stack exchange,提问作者MG.
相关产品推荐
相关产品推荐

