3

Question: How to remove previous route url from history so that browser "back" button skip it?

In my application if data is invalid or other issues - Angular performs redirection to error page. But if to press "Back" button in browser - user gets redirected to error page again and from there to error page. So it is kind of endless cycle.

The idea is to remove previous url (with invalid data) from history so previous redirect would lead to the page before url with invalid data.

We have some browser.location api in vanilla JS, but how to do that by Angular way?

Update: there are many ways to get previous url, like: How to determine previous page URL in Angular?. But how to set it?

Solution: I've tried to use Angular Location.replaceState() to override history. In some reason it just removed one history entry without replacing it: https://angular.io/api/common/Location#replaceState Similar behavior was in vanilla JS History.replaceState(): https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState

I end up with changing design to use skipLocationChange: true in NavigationExtras: https://angular.io/api/router/NavigationExtras so Bálint Réthy's answer fits best.

Alex Vovchuk
  • 2,828
  • 4
  • 19
  • 40
  • Please, try to order your question as it is hard to follow what you are trying to accomplish. Describe better the context, describe a bit what is the tasks and what are you trying to achieve, describe the problem and post some example code or working plunkr/stackblitz/snippet – ZetaPR Nov 21 '19 at 15:22
  • 1
    @ZetaPR, I've updated the question if it is more clear for you – Alex Vovchuk Nov 21 '19 at 15:31

3 Answers3

2

You need to use navigation options. When you get an error that navigates to error page, that should be implemented with NavigationExtras. There you can define skipLocationChange or replaceUrl.

  • skipLocationChange skips to push state into history when navigation changes
  • replaceUrl redefine the current state in the history

Code should look like something like this:

this.router.navigate(['/error'], { replaceUrl: true });

Documentation reference: https://angular.io/api/router/NavigationExtras

Bálint Réthy
  • 411
  • 1
  • 6
  • 25
  • 1
    skipLocationChange doesn't fit for me as at moment of redirection I don't know that url contains invalid data. – Alex Vovchuk Nov 21 '19 at 15:36
  • I guess it should be since it replaces the invalid state. So when the user press back it will backs to the previous right url state. ;) – Bálint Réthy Nov 21 '19 at 15:40
0

Angular route guard CanActivate method will help you solve our problem it will fire when user will navigate or try to navigate from one screen to another. it will also provide you the next url routes that you can easily manipulate according to your requirements. you just have to include route guard in provider and implement CanActivate route guard.

step 1-implement CanActivate interface

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    // here you can write you logic example-> you can navigate to some where else protect navigation
    console.log('AuthGuard#canActivate called');
    return true;
  }
}

step 2 -> tell your route table that you have a guard to protect your route :P

 import { AuthGuard }  from '../auth/auth.guard';

    const adminRoutes: Routes = [

    { path: 'crises', component: ManageCrisesComponent },
    { path: 'admin',  component: AdminComponent, canActivate: [AuthGuard]} // -->your Auth guard will get register here 
    ];

for more help refer - Angular Portal Medium

raj yadav
  • 204
  • 3
  • 10
  • Everything is ok with navigation. The question is in stored navigation three. To remove previous url from the three so by pressing "Back" in browser user would jump not to previous url but to pre- previous – Alex Vovchuk Nov 21 '19 at 15:51
  • thats what if you hit the back button (Back button in browser), canActivate method will get trigger where you can redirect or change URL, please correct me if i have understood the question wrong – raj yadav Nov 21 '19 at 16:45
0

For me, the back button is a matter of the browser and the user. I am going to explain my self, if the user wants to go back you should let them and that would be the proper way for me, the usual flow and how it is supposed to be done.

But in order to accomplish this you may do it like this:

In you error page you may use history.pushState doc: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

  history.pushState(null, null, window.location.href);  
ZetaPR
  • 964
  • 7
  • 32