我有一个带有“后退”按钮的表单。当用户按下后退按钮时,脚本转到上一页:
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/