Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Location back history

Tags:

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?

like image 455
Cequiel Avatar asked Jan 23 '18 11:01

Cequiel


People also ask

What is angular location?

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.

What is window location HREF in angular?

Window Location Href href property returns the URL of the current page.


1 Answers

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?

like image 123
paragonid Avatar answered Sep 19 '22 16:09

paragonid