0

I know there is an option to preserve a query param if the navigation is happening directly with routerLink or router. navigate method (through {queryParamsHandling: 'preserve'}) but I need the following: When the queryParam is set, I want to use it throughout the entire application. Is it possible to achieve it?

I have a webpage with a specific router configuration:

  {path: 'transport', component: TransportComponent},
  {path: 'events/:id', component: EventsComponent},
  {path: 'pages/:page', component: PagesComponent}

This is just a part of it, let's say regular routes.

My problem is that these links can be opened in 2 ways:

  1. They can be opened without a location in which case it would be localhost:4200/transport
  2. They can be opened with the location in which case it would be localhost:4200/transport?locationName

Location can be selected on home page.

So my idea was to save the location name in queryParam but I struggle to find a way to preserve on every route change

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
student23
  • 9
  • 1
  • 7
  • 1
    Does this answer your question? [How to keep query parameters in angular 5 on all routes by default?](https://stackoverflow.com/questions/47995412/how-to-keep-query-parameters-in-angular-5-on-all-routes-by-default) – Vedran Maric Nov 15 '20 at 22:55
  • Can you explain the use case for your requirement? Maybe there is a better way to preserve that state. – Silvermind Nov 15 '20 at 22:56
  • @VedranMaric Not really, this just preserves the params on direct routing as I explained in my post – student23 Nov 15 '20 at 23:01
  • @Silvermind I updated the post with the specific problem – student23 Nov 15 '20 at 23:13

1 Answers1

1

There is an extensive discussion about this here: Angular: configure default QueryParamsHandling

There's a directive that's applied to the a[routerLink] selector. The problem that surfaced was that if you extend the routerLinkDirective, the routerLinks inside a routerOutlet seem to have the correct url, but after clicking the link, the queryparams are lost.

The solution was to inject the routerLinkDirective rather than extending it

@Directive({
  selector: 'a[routerLink]'
})
export class QueryParamsHandlingDirective {
  constructor (routerLink: RouterLinkWithHref) {
    routerLink.queryParamsHandling = 'merge';
  }
}

Credits to @Andrei Gătej

Pieterjan
  • 2,738
  • 4
  • 28
  • 55
  • Looks good, I will try it. Thank you for the answer – student23 Nov 15 '20 at 23:45
  • The only limitation here (by angular) is that you cannot specify which queryparams should be preserved and which should be dropped when routerlinks are generated – Pieterjan Nov 16 '20 at 06:28