Angular:位置回溯历史

Ceq*_*iel 14 location back typescript angular

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

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

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

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

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');
}
Run Code Online (Sandbox Code Playgroud)

那可能吗?

par*_*nid 12

您可以查看历史记录window.history.length.因此你的功能看起来像

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

docs: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'])
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是有关如何确定以前网址的详细信息:如何确定Angular中的上一页网址?