27

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:

let userToken: string;
    this.sub = this.router
      .routerState
      .queryParams
      .subscribe(params => {
        userToken = params['token'];
        params['token'].remove();
      });

But obviously the remove function doesn't exist. Does someone have an alternative?

5
  • remove from where, query string? or from params object only? Commented Jul 4, 2016 at 14:14
  • from the params object so that it won't show up in the URL anymore. Commented Jul 4, 2016 at 14:28
  • Change it to unreadable format is better than deleting it. Commented Jul 4, 2016 at 15:11
  • running into the same issue, need to remove the queryparams so when I route to another page, the param is no long part of the url. did you find a solution? Commented Jul 6, 2016 at 18:58
  • Not yet, I edit the current url with window.location but when I route to another page the parameter is back. Commented Jul 7, 2016 at 7:23

10 Answers 10

56

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Oh yeah ! I was wondring about sending token JWT from backend to frontend and it looks like it is not only my problem. Thanks for your answer :)
Dependency Inject'ing :-) - so add it to the constructor in your component.
does not work in my project, I am using angular router and have routed path with param like: http://dev.somedomain.sk/parkzones?city=Trnava after removing param city via location.replaceState('city') I am getting result http://dev.somedomain.sk/city
@Luckylooke location:replaceState('city') doesn't remove the queryParam but it replaces the current route with the route in it. In your case you should use location.replaceState('parkzones')
@EinArzt aha, then it is not suitable for my usecase, because I need to remove param from many others, but I need the keep others there.. In my app I am setting multiple filters on data listing, I want to have them represented in url, I am able to add filter params into url, but not to remove them easily.
|
32

You can assign null to a specific queryParam :

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

1 Comment

I've used something like this this.router.navigate(['/home'], {queryParams: {verify_email_token: null}, queryParamsHandling: 'merge'}); But it does'nt work
10

Imperative method, but cleaner:

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

1 Comment

For me, I think this is the best answer, I added replaceUrl too so it become this._router.navigate(['.'], {relativeTo: this._route, queryParams: {}, replaceUrl: true})
4

UPDATE It is not necessary to add queryParams in rc6 anymore.

Not sure if it is the case:

After routing to a component with query params, all the other urls in this component contain the query params automatically. Anytime you navigate to another url the query params stay.

If so, one possible solution could be at query params on html tag

<a [routerLink]="['/abcd']" [queryParams]="{}">

If not, I am actually also interested in the answer :P

2 Comments

This works! Could be a pain however to add this to every single link of you have alot of them. But for now it is the best solution I guess.
This should NOT be the default behavior but at the moment (as of RC4) it seems like it is.... I find it abysmal.
4

HTML5 includes the history.pushState API, which allows you to add history entries and change the URL currently displayed in the browser. (Manipulating the browser history)

window.history.pushState('', 'title', '/expected-url');

You can use this line of code in your Angular2 application. This will just change the URL not state of the application. (results query param remove from given url)

Comments

3

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.

Comments

2

I use the router method navigateByUrl.

Alternate doc: Angular documentation

Keep in mind that the path you feed it is treated as absolute. You cannot use relative component routing with this method.

My use is I have a component that serves as an external callback for auth events, such as resetting the password and email validation. Once the operation is complete, any navigation action needs to occur happens through router.navigateByUrl(path)

2 Comments

This doesn't offer a solution. You would need a good method of getting the current route/url and removing the query parameter from that (which, as far as I know, doesn't exist in Angular2 at the moment).
I reverted the minus vote, since back in the day router.navigateByUrl() was the only option to remove queryParams. That was a bug in Angular2 RC4 and older. However, this method is now obsolete for removing query params, as you can now modify them also using router.navigate().
1
this.router.navigate([], {
  queryParams: {
    paramName: null,
    paramName2: null,
  },
  queryParamsHandling: 'merge'
})

1 Comment

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
0

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];
        }
    });

Comments

0

You can just set the queryParams object to be null manually if you need it to be a clearance programatically, rather than on the actual act of navigating as other answers suggestion. Eg:

this.alertClockoff = this.activatedRoute.snapshot.queryParams['alertClockoff'] || null;
if(this.alertClockoff == 'true') {
  Haptics.vibrate();
  setTimeout(() => {
    this.alertClockoff = null;
    // This line:
    this.activatedRoute.snapshot.queryParams = null;
  }, 5000);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.