Search code examples
angularangular-routerquery-string

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

  • I finally found what happened. The second navigation came from my cookie management (CookieComponent)

    ngAfterViewInit(): void {
        this.router.navigate([{ outlets: { popup: isDisplayed ? 'cookie' : null } }]);
    }
    

    I don't really get why this second navigation occurs only when there are queryParams on the page. But refactoring this code as follow solved my problem

    ngAfterViewInit(): void {
        if (display) {
          this.router.navigate([{ outlets: { popup: 'cookie' } }]);
        }
    }
    

    So if you have a weird behaviour with your queryParams on a page, first check in your app if you have some this.router.navigate that may have been called during the page reload !