Angular 5:进入父路由时导航至最后访问的子路由
实现Angular 5父路由自动导航至最后访问子路由的方案
针对你这个多层嵌套路由的场景,要实现进入父路由时跳转到用户最后访问的子路由,我们可以通过路由状态存储+父组件初始化时重定向的方式来搞定,具体步骤如下:
1. 创建路由历史服务(用于存储最后访问的子路由)
首先需要一个全局服务来保存用户最后访问的子路由路径,因为这个状态需要在多个组件间共享:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' // Angular 5+ 支持这种全局服务提供方式 }) export class RouteHistoryService { private lastVisitedPath: string | null = null; setLastVisitedPath(path: string): void { this.lastVisitedPath = path; } getLastVisitedPath(): string | null { return this.lastVisitedPath; } }
2. 记录子路由的访问路径
接下来需要追踪用户访问过的子路由,这里有两种实现方式:
方式一:在子组件中单独记录(适合子路由较少的情况)
在所有需要追踪的子组件(比如PartnersBranchesComponent、RegisterPartnersBranchesComponent)的ngOnInit钩子中,保存当前路由的相对路径:
以RegisterPartnersBranchesComponent为例:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { RouteHistoryService } from '../route-history.service'; @Component({ selector: 'app-register-partners-branches', templateUrl: './register-partners-branches.component.html', styleUrls: ['./register-partners-branches.component.css'] }) export class RegisterPartnersBranchesComponent implements OnInit { constructor( private route: ActivatedRoute, private routeHistory: RouteHistoryService ) { } ngOnInit() { // 拼接当前相对于父路由(system-variables)的完整路径 const fullRelativePath = this.route.pathFromRoot .slice(1) // 剔除根路由节点 .map(segment => segment.url.join('/')) .join('/'); this.routeHistory.setLastVisitedPath(fullRelativePath); } }
方式二:全局监听路由事件(适合子路由较多的情况)
如果子路由数量多,不想在每个组件里重复写逻辑,可以在根组件或路由模块中监听路由导航完成事件,统一记录路径:
// 在app.component.ts中 import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { RouteHistoryService } from './route-history.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor( private router: Router, private routeHistory: RouteHistoryService ) {} ngOnInit() { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { // 提取/system-variables后的路径片段 const systemVarPathPrefix = '/system-variables'; const pathStartIndex = event.url.indexOf(systemVarPathPrefix); if (pathStartIndex !== -1) { const relativePath = event.url.slice(pathStartIndex + systemVarPathPrefix.length); // 仅记录非空路径(避免刚进入父路由时的空路径) if (relativePath) { this.routeHistory.setLastVisitedPath(relativePath); } } } }); } }
3. 修改父组件实现自动重定向
在最顶层的父组件SystemVariablesComponent中,初始化时读取历史路径,存在则导航到该路径,否则走默认的初始路由:
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { RouteHistoryService } from './route-history.service'; @Component({ selector: 'app-system-variables', templateUrl: './system-variables.component.html', styleUrls: ['./system-variables.component.css'] }) export class SystemVariablesComponent implements OnInit { constructor( private router: Router, private route: ActivatedRoute, private routeHistory: RouteHistoryService ) { } ngOnInit() { const lastPath = this.routeHistory.getLastVisitedPath(); if (lastPath) { // 相对父路由导航到历史路径 this.router.navigate([lastPath], { relativeTo: this.route }); } else { // 无历史记录时,导航到默认的初始子路由 this.router.navigate([ 'partners-variables/partners-branches/register-partners-branches' ], { relativeTo: this.route }); } } }
4. 调整路由配置(可选)
因为父组件已经处理了重定向逻辑,你可以把路由配置里的多层默认redirectTo移除,让配置更简洁:
{ path: 'system-variables', component: SystemVariablesComponent, children: [ { path: 'partners-variables', component: PartnersVariablesComponent, children: [ { path: 'partners-branches', component: PartnersBranchesComponent, children: [ { path: 'register-partners-branches', component: RegisterPartnersBranchesComponent } ] } ] } ] }
这样调整后,用户每次进入/system-variables时,都会自动跳转到最后访问过的子路由,第一次访问则进入默认的初始路由。
内容的提问来源于stack exchange,提问作者Felipe Micali
相关产品推荐
相关产品推荐

