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:
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?
Location is a service available in Angular 2+ apps that makes it easy to interact with the current URL path. For most navigation needs, the Angular router is the correct solution, but in a few cases the location service is needed to affect the url without involving the router.
Window Location Href href property returns the URL of the current page.
You could check the history with window.history.length
. Therefore your function would look like
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
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With