【问题标题】:Angular: Location back historyAngular:位置回溯历史
【发布时间】:2025-12-11 13:10:01
【问题描述】:

我有一个带有“返回”按钮的表单。当用户按下后退按钮时,脚本会转到上一页:

import { Location } from '@angular/common';

// In a place in La Mancha, whose name I do not want to remember...
this.location.back();

但是,当用户直接在地址栏中输入 url 时会发生什么?在这些情况下,应用程序会返回浏览器的主页。我想要这样的东西:

import { Location } from '@angular/common';

// In a place in La Mancha, whose name I do not want to remember...
if (this.location.history.length > 0) {
    this.location.back();
} else {
    this.router.navigate(['/home');
}

这可能吗?

【问题讨论】:

    标签: angular typescript location back


    【解决方案1】:

    您可以使用window.history.length 查看历史记录。因此你的函数看起来像

    goBack() {
      if (window.history.length > 1) {
        this.location.back()
      } else {
        this.router.navigate(['/home'])
      }
    }
    

    文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/history

    它的问题是某些浏览器(例如chrome)将初始页面存储在历史记录中,因此window.history.length > 1您将被发送到浏览器的初始页面。

    在我的应用程序中,我必须实现额外的逻辑来确定在类似情况下用户应该去哪里。

    goBack() {
      if (this.isHistory) {
        this.router.navigate(['/history'])
      } else {
        this.router.navigate(['/home'])
      }
    }
    

    以下是有关如何确定您之前的 URL 的详细信息:How to determine previous page URL in Angular?

    【讨论】: