Skip to content

Allow router configuration so that preserveQueryParams is true by default #12664

Closed

Description

@alexeagle

Currently the router allows an individual navigation to preserve the query params (eg. Google's common hl query param)
This feature request is to allow the router to be configured so that this behavior takes place for all navigation.

Activity

  1. added
    feature
    on Nov 2, 2016
  2. removed their assignment
    on Nov 16, 2016
  3. mattrowsboats commented on May 3, 2017

    @mattrowsboats

    I'd also like to know. The workarounds listed on that stack overflow are for once you're already inside the application. There is no solution if your route into the application has a query parameter. The app strips it on app entry.

  4. dan3721 commented on Jul 17, 2017

    @dan3721

    There is queryParamsHandling: 'preserve' on NavigationExtras which handles this for programmatic navigation but, I do not see a global level configuration. Without a global setting all the links embedded in the views would also need to be touched to add that config too right?

  5. karsunke commented on Oct 10, 2017

    @karsunke

    I know that the angular team is busy as hell, but can we get at least a comment if this will be supported some time in the future?

    My solution is to subscribe to the queryParameters and add them if they do not exist:

        constructor(private router: Router, private activatedRoute: ActivatedRoute) {
            activatedRoute.queryParams.subscribe((params: Params) => {
    
                const parameter = params['value_which_should_be_kept'];
    
                if (!parameter && this.currentValue) {
    
                    const queryParams = {};
                    queryParams['value_which_should_be_kept'] = this.currentValue;
    
                    this.router.navigate([], {
                        queryParams: queryParams,
                        queryParamsHandling: 'merge'
                    });
                }
    
            });
        }
    
  6. voithos commented on Nov 21, 2017

    @voithos
    Contributor

    For what it's worth, I had filed a duplicate feature request earlier, which had some work done on it but was closed because it was deemed that a complete solution wasn't possible at the time, and not enough users needed such a thing. #16558

  7. Joniras commented on Jan 5, 2018

    @Joniras

    @karsunke i used your workaround and its great working until a user wants to go back via the back button of the browser.
    Because the URL always just goes back to /foo/bar just to instantly change to /foo/bar?some=name again. I tried to do a workaround but its getting smelly. (workaround-workaround-workaround).

    I need this global configuration of queryParamsHandling!

  8. chriszrc commented on Jan 9, 2018

    @chriszrc

    As noted in the linked issue #13315, you can keep the parameter if your redirectTo is not absolute. Then you can subscribe to the activatedRoute and get the query params-

  9. Joniras commented on Jan 9, 2018

    @Joniras

    My Issue has nothing to do with redirectTo. I dont use it anywhere in my project.

    My Current Workaround for preserving query params in a global way ( from SO ):

    @Directive({
      selector: 'a[routerLink]'
    })
    export class PreserveQueryParamsDirective {
      constructor(private link: RouterLinkWithHref, private route: ActivatedRoute ) {
        this.route.queryParamMap.subscribe(queryParams => {
          this.link.queryParams = Object.assign({}, this.route.snapshot.queryParams);
        });
      }
    }

    And this is not a clean solution for me.

  10. added this to the Backlog milestone on Jan 23, 2018
  11. 54 remaining items

  12. smichel-amiltone commented on Sep 28, 2023

    @smichel-amiltone

    I use this and provide the home path to do it only on this path !

    app.module.ts

    ...
        {
          provide: LocationStrategy,
          useClass: PreserveQueryParamsPathLocationStrategy,
        },  
    ...    
    

    Class PreserveQueryParamsPathLocationStrategy

    import { APP_BASE_HREF, PathLocationStrategy, PlatformLocation } from '@angular/common';
    import { Inject, Injectable, Optional } from '@angular/core';
    import { UrlSerializer } from '@angular/router';
    import { RoutePathFull } from 'src/app/core/enums/route.enums';
    
    @Injectable()
    export class PreserveQueryParamsPathLocationStrategy extends PathLocationStrategy {
      private get search(): string {
        return this.platformLocation?.search ?? '';
      }
    
      constructor(
        private platformLocation: PlatformLocation,
        private urlSerializer: UrlSerializer,
        @Optional() @Inject(APP_BASE_HREF) _baseHref?: string,
      ) {
        super(platformLocation, _baseHref);
      }
    
      prepareExternalUrl(internal: string): string {
        const path = super.prepareExternalUrl(internal);
        const urlTree = this.urlSerializer.parse(path);
    
        // if not on the home page juste do nothing and return
        const urlToString = urlTree.toString();
        if (!urlToString.includes(RoutePathFull.Home)) {
          return urlToString;
        }
    
        const nextQueryParams = urlTree.queryParams;
        const existingURLSearchParams = new URLSearchParams(this.search);
        const existingQueryParams = Object.fromEntries(existingURLSearchParams.entries());
        urlTree.queryParams = { ...existingQueryParams, ...nextQueryParams };
    
        return urlTree.toString();
      }
    }
    
  13. antoineaws commented on Oct 3, 2023

    @antoineaws

    Weird.. I did add the above location strategy to app.module.ts in providers:

    providers: [
        {
          provide: LocationStrategy,
          useClass: PreserveQueryParamsPathLocationStrategy,
        },
      ]

    and referenced the above function and I am still getting this weird behavior... Attached a small clip.

    Screen.Recording.2023-10-03.at.9.47.27.AM.mov
  14. smichel-amiltone commented on Oct 3, 2023

    @smichel-amiltone

    Weird.. I did add the above location strategy to app.module.ts in providers:

    providers: [
        {
          provide: LocationStrategy,
          useClass: PreserveQueryParamsPathLocationStrategy,
        },
      ]

    and referenced the above function and I am still getting this weird behavior... Attached a small clip.
    Screen.Recording.2023-10-03.at.9.47.27.AM.mov

    Do you remove / update the part where i only keep the queryParams when the route match my home route ?

        // if not on the home page juste do nothing and return
        const urlToString = urlTree.toString();
        if (!urlToString.includes(RoutePathFull.Home)) {
          return urlToString;
        }
    
    
  15. laurentgrenier commented on Dec 13, 2023

    @laurentgrenier

    I've struggled for hours with that too. None of the solution posted here matches exactly with my application. I've finally implement a mix of proposals and the result is like grandmother's medicine : effective but ugly.
    A specific implementation of the hash location strategy that store the params (...)

    import { HashLocationStrategy, APP_BASE_HREF, PlatformLocation } from '@angular/common';
    import { Optional, Inject, Injectable } from '@angular/core';
    
    
    @Injectable()
    export class HashPreserveQueryLocationStrategy extends HashLocationStrategy {
      private readonly search: string;
      private readonly currentQueryParams: string;
    
      constructor(
        _platformLocation: PlatformLocation,
        @Optional() @Inject(APP_BASE_HREF) _baseHref?: string,
        ) {
        super(_platformLocation, _baseHref);
        
        this.search = window.location.search || '';
      }
      
    
      prepareExternalUrl(internal: string): string {
        const hash = super.prepareExternalUrl(internal);    
        const currentQueryParams = new URLSearchParams(this.search);
        const params_entries = Object.fromEntries(currentQueryParams.entries());    
        sessionStorage.setItem("url-params", JSON.stringify(params_entries))    
    
        return hash + this.search    
      }
    }

    Then, I read the params from where I use them:

    getQueryParamsWorkaround(){
            let params = sessionStorage.getItem("url-params")
            if (params){
                sessionStorage.removeItem("url-params")
                return JSON.parse(params)
            } else {
                return null
            }
            
        }

    I'm so sorry for state of the art :)

  16. shyamal890 commented on Jul 19, 2024

    @shyamal890

    With so many people looking for a solution, an update on the following would really help us move in a particular direction:

    1. How important is this issue for the Angular team?
    2. If its high priority what's the blocker?
    3. Can we expect a resolution in next release? If not, is there a tentative timeline for this?
  17. atscott commented on Jul 19, 2024

    @atscott
    Contributor

    @shyamal890 See #12664 (comment). It's quite unclear what developers are actually looking for in a solution here. The simple "solution" is easy and could be released if there were a clear signal that this is sufficient for the majority of people upvoting this issue. A more robust solution for query params alone can likely be achieved through existing APIs. Developing an entirely new feature for managing the query params would likely never be prioritized without overwhelming support.

  18. shyamal890 commented on Jul 30, 2024

    @shyamal890

    @atscott defaultQueryParamsHandling would be great. We can then decide to remove query params we don't need in a particular route.

  19. added a commit that references this issue on Aug 2, 2024
    6c76c91
  20. bennadel commented on Aug 29, 2024

    @bennadel

    I'm not sure if this is exactly the same issue for me, but it seems to be relevant. I'm using a Hash-based location strategy and I was seeing the index page, the path info, and the query-string of the host page being stripped-out. For example, if I landed on this resource:

    /path/to/app/index.cfm/path/info?hello=world#/angular/route

    Most of the resource information was being stripped out (presumably with a push-state) to become:

    /path/to/app/#/angular/route

    I was able to "fix" this by adding the entire "internal URL" to the <base href> tag:

    <base href="/path/to/app/index.cfm/path/info?hello=world">

    However, this broke the <script> tag sources that were injected into the page. So, I also had to include a --deploy-url in my build script that prefixed all injected script src values to the right directory:

    ng build --configuration production --deploy-url=/path/to/app/

    The whole thing seems like a house-of-cards (possibly because I don't fully understand the routing configuration). It's unclear to me why any host URL alterations would take place at all when using Hash-based routing. It seems that Angular should only ever touch the fragment of the URL and nothing else.

  21. angular-automatic-lock-bot commented on Sep 29, 2024

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  22. locked and limited conversation to collaborators on Sep 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: routerfeaturefeature: under considerationstate: Needs Design

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions