How to add / update query parameters in Angular2

I am using query parameters in my application that I want to save / update when navigating and updating settings. I can add the parameter without any problem by doing the following.

onNavigate() { this.router.navigate(['reports'], {queryParams: {'report': this.chart}, preserveQueryParams:true}); } 

However, I want to be able to change the report parameter and add new parameters to the URL in my application.

Using preserveQueryParams: true makes my parameters read-only. I want to be able to update the current settings and add new ones without losing anything if I do not clear them.

How can I do this without losing my current settings?

+5
source share
2 answers

I think preserveQueryParams not intended to add / update queryParams on behalf of the application.

You need to write your own logic to get the existing query parameters and update it according to your requirement, and then skip during navigation.

  this.route.queryParams.subscribe(qparams => { this.currentQueryParams= qparams; }); updatedqueryParams = // use this.currentQueryParams update it to append\update new stuff let navigationExtras: NavigationExtras = { queryParams: updatedqueryParams }; // Navigate to the login page with extras this.router.navigate(['<some path>'], navigationExtras); 

for preserveQueryParams designed to pass the current global Params requests you are heading to

therefore, if the current URL

  dashboard?debug=true&somevar=1 

and you write something like below

  this.router.navigate(['admin'], { preserveQueryParams: true } ); 

there will be a new route, so it saves the request parameters.

 admin?debug=true&somevar=1 

Hope this helps!

0
source

preserveQueryParams is deprecated, use queryParamsHandling instead.

queryParamsHandling is used to configure a strategy for processing query parameters for the next navigation.

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

0
source

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


All Articles