Angular:位置回溯历史

标签 angular typescript location back

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

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');
}

这可能吗?

最佳答案

您可以使用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'])
  }
}

这里详细介绍了如何确定您之前的网址:How to determine previous page URL in Angular?

关于Angular:位置回溯历史,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48400305/

相关文章:

Angular 变量错误未定义

reactjs - 获取对组件类实例的引用

java - 从启动的 HTML 文件将数据检索到 Java 应用程序中

javascript - 填满所有字段后的事件

Angular 2+ 将指令传递给自定义组件

javascript - 区域.js : Uncaught RangeError: Maximum call stack size exceeded

android - 安装在 sdcard 上的应用程序的 .apk 位置在哪里?

javascript - Angular HTTP 请求延迟拦截器未按预期工作

typescript - ts-loader -> file-loader 不解析 require dependencies

mysql - 如何在MySQL中用公里搜索附近的位置