-1

So I have to "disable" clicking browser back button on several routes ans the request to backeng has been sent and it's not consistent to create a ton of similar requests to api. Basically I'm using

this.location.onPopState(() => {
  console.log('pressed back!');
  this.router.navigateByUrl('url', { skipLocationChange: true })
});

in the constructor to detect back button click and the problem is that when I click back I'm not redirected to the needed page, but to previous one. I've tried location.here= url; but it reloads window and still displays previous page for a second. Please, if you have any suggestions I will appreciate any help.

Hack Wiz
  • 15
  • 5

1 Answers1

0

I don't think it is a good idea to block the back button. You can use a caching mechanism for the requests so it won't send the request to server every time, but getting the latest response. Please check this example:

const URL = 'https://api.punkapi.com/v2/beers';
@Injectable({
  providedIn: 'root'
})
export class HttpService {
  public responseCache = new Map();constructor(private http: HttpClient) {}public getBeerList(): Observable<any> {
    const beersFromCache = this.responseCache.get(URL);
    if (beersFromCache) {
      return of(beersFromCache);
    }
    const response = this.http.get<any>(URL);
    response.subscribe(beers => this.responseCache.set(URL, beers));
    return response;
  }
}

If you still want your solution to block the user from going back, you will need to use Guards in order to cancel the navigation.

@Injectable()
export class MyGuardService implements CanActivate {  
  constructor(public auth: AuthService, public router: Router) {} 
    canActivate(): boolean {
      return !this.myService.stillDontWantToGoBack()
    }}

This will be for all navigations, if you still want only the back, you will need to check if the URL you are going to is the same as previousUrl.

my-service.service.ts

previousUrl: string;
constructor(router: Router) {
  router.events
    .filter(event => event instanceof NavigationEnd)
    .subscribe(e => {
      console.log('prev:', this.previousUrl);
      this.previousUrl = e.url;
    });
} 

in my-guard.guard.ts

canActivate(route: ActivatedRouteSnapshot) {
  return route.url !== this.myService.previousUrl;
}

References and more info:

yazantahhan
  • 2,950
  • 1
  • 13
  • 16