When working with Angular, it's important to always keep track of the previous URL. One way to achieve this is by creating a service that handles both the current and previous URLs as shown below:
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;
}
}
In your component, utilize the RouterService like so:
constructor(private routerService: RouterService) {}
navigateBack() {
this.previousQueryParams = this.routerService.getPreviousUrl().split('?')[1]; // extract query params
const newUrl = `your new url?${previousQueryParams}`;
// create queryParamsObject here
this.router.navigate([`${newUrl}`], queryParamsObject)
}