Remove a parameter from queryParams angular 2

前端 未结 9 1218
半阙折子戏
半阙折子戏 2021-01-31 09:42

I navigate to a certain page in my app with a query parameter. After I get the parameter from the URL I want to delete it, ideally I would have this:



        
相关标签:
9条回答
  • 2021-01-31 10:18
    this.router.navigate([], {
      queryParams: {
        paramName: null,
        paramName2: null,
      },
      queryParamsHandling: 'merge'
    })
    
    0 讨论(0)
  • 2021-01-31 10:22

    Imperative method, but cleaner:

    this.router.navigate(['.'], { relativeTo: this.route, queryParams: {} });

    0 讨论(0)
  • 2021-01-31 10:27

    Just in case people find this thread (like I did). I have the scenario that I receive a JWT token in a query string (/login?jwt=token). I needed to fetch this token (and store it etc), but then needed to make sure that it got safely removed from the URL. Reloading the login route (by using this.router.navigate(['login']) works in principe, however, the user can then use the browser back button, basically replaying the token login.

    I solved this by not using the navigate but by DI'ing the 'Location' service (from @angular/common). This service has a replaceState method, which completely removes the token from the history as well as from the URL

     this.location.replaceState('login')
    

    Hope that helps someone.

    0 讨论(0)
  • 2021-01-31 10:29

    I would suggest this way that is compatible with all routing strategies of Angular X:

        this.route.queryParams.subscribe(params => {
            let token = params['jwt'];
            if (token) {
                this.cache.set({t: 't'}, token);
                window.location.href = this.router.url.split('?')[0];
            }
        });
    
    0 讨论(0)
  • 2021-01-31 10:32

    You can assign null to a specific queryParam :

    this.router.navigate([], {queryParams: {page: null}, queryParamsHandling: 'merge'});

    0 讨论(0)
  • 2021-01-31 10:32

    I was looking for answer like this when I wanted to remove access_token parameter from url. If you just want remove one parameter and retain the other parameters.

    setTimeout(() => {
      let urlWithoutAccessToken = this.router.url.replace(new RegExp('.access_token=' + idToken), '');
      this.router.navigateByUrl(urlWithoutAccessToken);
    }, 0);
    

    The setTimeout was needed for some reason, the navigateByUrl didn't work without it.

    0 讨论(0)
提交回复
热议问题