Angular2 how to clear url request parameters on a router

I am struggling with cleaning URL parameters while navigating in Angular 2.4.2. I tried to set each parameter to clear the parameters in the navigation line below, or any mix in it using navigation or navigateByUrl, but I can’t figure out how to do this.

this.router.navigateByUrl(this.router.url, { queryParams: {}, preserveQueryParams: false }); 

As an example, I am on the route /section1/page1?key1=abc&key2=def and want to stay on the same route but delete all URL parameters, so the end result should be /section/page1

+13
source share
5 answers

As DeborahK pointed out, when I went to this.router.url, this URL already had url parameters built in. To solve, I removed the parameters from the URL as a string, and then used navigateByUrl to go there.

 let url: string = this.router.url.substring(0, this.router.url.indexOf("?")); this.router.navigateByUrl(url); 
+15
source

Using navigateByUrl will discard the request parameters if you pass it a URL without request parameters.

Or you could try:

 this.router.navigate(this.router.url, { queryParams: {}}); 

NOTE: navigate , not navigateByUrl

It works?

+12
source

If you do not want to reload the page, you can also use Location

 import { Location } from '@angular/common'; [...] this.location.replaceState(this.location.path().split('?')[0], ''); 

this.location.path() provides you with the current path. Can you remove the parameters by resetting the path to the page with everything in the URL to ? ,

+7
source

Use the skipLocationChange parameter and it will not show the parameters: suppose your URL

HTTP: // local / view

Now something in your code sets the request parameters

? D = & all viewtype = general

without skipLocationChange your URL in the browser (after calling the navigation) will be:

HTTP: // local / view q = all & viewtype = general

with skipLocationChange: true, this remains

HTTP: // local / view

 let qp = { q : "all" , viewtype : "total" } this.router.navigate(['/view'], { queryParams: qp,skipLocationChange: true }); 
+5
source

You can add replaceUrl: true to the optional replaceUrl: true navigation. Thus, the router will go to the same page, but you will still remain in the same state in the history with missing url parameters, while at the same time allowing you to return to the previous route.

From the docs:

Moves when replacing the current state in history.

 this.router.navigate([], { replaceUrl: true}); 
+2
source

Source: https://habr.com/ru/post/1267243/


All Articles