You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 4应用中如何返回用户之前访问的路由?

在Angular 4中回溯用户路由访问路径的实现方案

当然可以实现啦!在Angular 4里追踪用户的路由访问路径、让未授权页面跳转回之前的页面完全没问题,我给你分享几个实用的实现思路:

1. 用路由事件监听记录历史路径

你可以创建一个专门的路由历史服务,通过监听Angular的路由事件来自动记录用户访问过的页面路径。

步骤1:创建路由历史服务

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class RouteHistoryService {
  private history: string[] = [];

  constructor(private router: Router) {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((event: NavigationEnd) => {
      // 排除未授权页和登录页,避免循环记录
      if (!event.url.includes('/unauthorized') && !event.url.includes('/login')) {
        // 避免重复记录同一页面
        if (this.history[this.history.length - 1] !== event.urlAfterRedirects) {
          this.history.push(event.urlAfterRedirects);
        }
      }
    });
  }

  // 获取上一个有效的路由路径
  getPreviousUrl(): string {
    // 移除最后一条(当前未授权页的记录),取前一条;没有记录就返回首页
    this.history.pop();
    return this.history.length > 0 ? this.history[this.history.length - 1] : '/home';
  }
}

步骤2:在未授权页面使用服务

在你的未授权组件里注入这个服务,点击确认按钮时调用方法跳转:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { RouteHistoryService } from './route-history.service';

@Component({
  selector: 'app-unauthorized',
  templateUrl: './unauthorized.component.html'
})
export class UnauthorizedComponent {
  constructor(private router: Router, private routeHistory: RouteHistoryService) {}

  onConfirm(): void {
    const previousUrl = this.routeHistory.getPreviousUrl();
    this.router.navigateByUrl(previousUrl);
  }
}

2. 在403拦截时直接记录当前路由

如果你的403是通过HTTP拦截器捕获的,那可以在拦截器里直接记录当前激活的路由,这样更精准:

步骤1:修改HTTP拦截器

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { Router } from '@angular/router';
import { RouteHistoryService } from './route-history.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(
    private router: Router,
    private routeHistory: RouteHistoryService
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 403) {
          // 记录当前正在访问的路由路径
          const currentUrl = this.router.url;
          this.routeHistory.setPreviousUrl(currentUrl); // 需要给服务新增这个方法
          this.router.navigate(['/unauthorized']);
        }
        return throwError(error);
      })
    );
  }
}

步骤2:更新路由历史服务

给RouteHistoryService添加手动设置路径的方法:

private previousUrl: string = '/home';

setPreviousUrl(url: string): void {
  this.previousUrl = url;
}

getPreviousUrl(): string {
  return this.previousUrl;
}

这样当用户触发403时,会直接记录下当时正在访问的页面,在未授权页点击确认后就能精准返回啦。

注意事项

  • 记得在模块里注册HTTP拦截器(如果路由历史服务不是providedIn: root,也要一并注册)
  • 可以根据业务需求调整需要排除的页面(比如注册页、密码重置页等)
  • 如果用户直接输入未授权页的URL,没有历史记录的话,就默认跳转首页,这个逻辑已经包含在上面的代码里了

内容的提问来源于stack exchange,提问作者User 5842

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:15:52