Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 router keep query string

I wrote an Angular2 (v2.0.1) application that makes use of the router. The website is loaded with several query string parameters, so the full URL initially looks like this:

https://my.application.com/?param1=val1&param2=val2&param3=val3 

In my route configuration, I have an entry which redirects an empty route:

const appRoutes: Routes = [     {         path: '',         redirectTo: '/comp1',         pathMatch: 'full'     },     {         path: 'comp1',         component: FirstComponent     },     {         path: 'comp2',         component: SecondComponent     } ]; 

My problem is, that after the app has been bootstrapped, the URL does not contain the query parameters anymore, instead it looks like this:

https://my.application.com/comp1 

Is there any way I can configure the router so that it keeps the initial query string when navigating?

Thank you
Lukas

like image 575
Lukas Kolletzki Avatar asked Oct 06 '16 14:10

Lukas Kolletzki


People also ask

How do I pass a query parameter in GET request?

To send query parameters in a POST request in JavaScript, we need to pass a body property to the configuration object of the Fetch API that matches the data type of the "Content-Type" header. The body will always need to match the "Content-type" header.

How do I get data from query params in Angular 6?

import ActivatedRoute from '@angular/router'. Inject ActivatedRoute class in constructor. Access queryParams property of ActivatedRoute class which returns an observable of the query parameters that are available in the current URL route.

How do you query parameters in a URL?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.


1 Answers

I don't think there is a way to define that in the routes configuration.

Currently it is supported for routerLinks and imperative navigation to enable

  • preserveQueryParams and
  • preserveFragment

You can add a guard to the empty path route, where in the guard navigation to the /comp1 route is done.

router.navigate(['/comp1'], { preserveQueryParams: true }); //deprecated. see update note 
router.navigate(['/comp1'], { queryParamsHandling: "merge" }); 

There is a PR to allow to configure preserveQueryParams globally.

Update note: from https://angular.io/api/router/NavigationExtras, preserveQueryParams is deprecated, use queryParamsHandling instead

like image 55
Günter Zöchbauer Avatar answered Sep 20 '22 15:09

Günter Zöchbauer