Oleg Bondarenko
Oleg Bondarenko

Reputation: 1820

Go back location for returning to previous different page not the same one with different query parameters

For changing sate location back to 1 step in angular we could use something like that this.location.back();.

That works fine while system does not use redirection to the same url but with different query parameters. In these case step back returns to the same page but with the previous set of query parameters.

My question is how we could step back to different previous page (url) but not to the same page with previous set of query parameters.

Upvotes: 0

Views: 2376

Answers (1)

Fateh Mohamed
Fateh Mohamed

Reputation: 21367

first of all you have always to get the previous url, you can create a service where you get always the current and the previous url like this:

import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';

@Injectable({
 providedIn: 'root'
})

export class RouterService {

 private previousUrl: string = undefined;
 private currentUrl: string = undefined;

 constructor(private router: Router) {
  this.currentUrl = this.router.url;
  router.events.subscribe(event => {
   if (event instanceof NavigationEnd) {
     this.previousUrl = this.currentUrl;
     this.currentUrl = event.url;
   }
  });
 }

 public getPreviousUrl() {
   return this.previousUrl;
 }
}

and in your component:

constructor(private routerService: RouterService) {}

navigateBack() {
  this.previousQueryParams = this.routerService.getPreviousUrl().split('?')[1]; // get query params
  const newUrl = `your new url?${previousQueryParams}`;

  // you can create queryParams object here "queryParamsObject"

  this.router.navigate([`${newUrl}`], queryParamsObject)
}

Upvotes: 1

Related Questions