'Page refresh removes queryParams Angular Router

I access to an angular component with a route myApp/contact with some query params like so

<div routerLink="../contact" [queryParams]="{ filter: 'myFilter' }"> </div>

The query params are saved in a router state (implementation of RouterStateSerializer) so I can access them from my component and then display them. When I navigate in the component, the url is now myApp/contact?filter=myFilter, which is good.

  • If I refresh the page, the url is now myApp/contact without the queryParams but I can still see them displayed on the page.
  • If I now refresh the page a second time, the url is again myApp/contact but now the queryParams are null when displayed on the page (which is logical because they weren't in the url anymore)

I noticed that when the route to myApp/contact is navigated, an another route request is made straight after @ngrx/router-store/navigated (see this 2nd request on capture below). I do not know where this second navigation request comes from, but it is during this one that the queryParams seem to be lost.

The question is, why my queryParams disappear when I refresh the page ? Is it cause of a configuration somewhere ? Why are there two navigation requests ?

enter image description here

These "2 navigation requests" occur only when I refresh this component page => none of my other pages have this behaviour (and I suspect it is because there are queryParams on this page)

I also have another Angular app which has some queryParams on some pages and I don't have the same behaviour when I refresh the page => the queryParams stay in the url, no matter the number of time I refresh the page



Solution 1:[1]

By default query parameters are lost on subsequent navigation requests. Set the queryParamsHandling to preserve to keep them

<div routerLink="../contact" [queryParams]="{ filter: 'myFilter' }" queryParamsHandling="preserve"> </div>

Solution 2:[2]

I'm not getting this behaviour, my guess is you're doing something funky in the component. Access your query params in your component (whichever is connected to the /component path) using the ActivatedRoute service.

  filter = '';

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.filter = this.route.snapshot.queryParams['filter'];
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SWilko
Solution 2 Chris Hamilton