typescript Angular:位置回溯历史
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48400305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular: Location back history
提问by Cequiel
I have a form with a "back" button. When the user presses the back button, the script goes to the previous page:
我有一个带有“后退”按钮的表单。当用户按下后退按钮时,脚本会转到上一页:
import { Location } from '@angular/common';
// In a place in La Mancha, whose name I do not want to remember...
this.location.back();
But, what happens when the user directly enters the url in the address bar? In those cases the application goes back to the Browser's homepage. I would like something like this:
但是,当用户直接在地址栏中输入 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');
}
Is that possible?
那可能吗?
回答by paragonid
You could check the history with window.history.length
. Therefore your function would look like
您可以使用window.history.length
. 因此你的功能看起来像
goBack() {
if (window.history.length > 1) {
this.location.back()
} else {
this.router.navigate(['/home'])
}
}
docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/history
文档:https: //developer.mozilla.org/en-US/docs/Web/API/Window/history
The problem with it is that some browsers (e.g. chrome) store initial page in the history, so window.history.length > 1
and you will be sent to browser's initial page.
它的问题在于某些浏览器(例如 chrome)在历史记录中存储初始页面,因此window.history.length > 1
您将被发送到浏览器的初始页面。
In my application I had to implement additional logic to determine where should user go in similar case.
在我的应用程序中,我必须实现额外的逻辑来确定在类似情况下用户应该去哪里。
goBack() {
if (this.isHistory) {
this.router.navigate(['/history'])
} else {
this.router.navigate(['/home'])
}
}
Here's details on how to determine what was your previous URL: How to determine previous page URL in Angular?
以下是有关如何确定您以前的 URL 的详细信息:如何在 Angular 中确定上一页 URL?