64

Im using this:

    import { HttpParams } from '@angular/common/http';
    let params = new HttpParams();
    params.append('newOrdNum','123');

But this is not working, i dont append param in url. Any suggestion?

Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
None
  • 8,817
  • 26
  • 96
  • 171
  • You want param like https://example.com/newordnum/123? – Salim Ibrohimi Sep 14 '17 at 08:11
  • 2
    Possible duplicate of [Why HttpParams doesn't work in multiple line in angular 4.3](https://stackoverflow.com/questions/45459532/why-httpparams-doesnt-work-in-multiple-line-in-angular-4-3) – Jota.Toledo Sep 14 '17 at 08:11
  • i want to append on existing params. I have something like this : example.com?param1=111 and now i want to append to get example.com?param1=111&newOrdNum=123 – None Sep 14 '17 at 08:14
  • @Jota.Toledo its not add param in url with your example – None Sep 14 '17 at 08:16
  • Are you trying to send a request with query parameters or to change the current state of the browser URL? If its the second, then you need to explain better what you are trying to archive – Jota.Toledo Sep 14 '17 at 08:19
  • i just want to append param to url...i'm gona handle that param on some other step..but right now just to append on existing url where i have other params – None Sep 14 '17 at 08:20
  • when your query params are changed, does that reflect in the url as well? – Tisha Dec 08 '19 at 13:28

7 Answers7

114

This could be achieved by using the Router class:

Using a component:

import { Router, ActivatedRoute } from '@angular/router';

@Component({})
export class FooComponent {
   constructor(
     private _route: ActivatedRoute,
     private _router: Router
   ){}

   navigateToFoo(){
     // changes the route without moving from the current view or
     // triggering a navigation event,
     this._router.navigate([], {
      relativeTo: this._route,
      queryParams: {
        newOrdNum: '123'
      },
      queryParamsHandling: 'merge',
      // preserve the existing query params in the route
      skipLocationChange: true
      // do not trigger navigation
    });
   }
}

For more info check this book and the angular Router API

bachonk
  • 3,924
  • 1
  • 14
  • 14
Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
  • 1
    should I be able to see it in the URL or this is behind the scene? – Omar Apr 26 '18 at 20:56
  • 4
    when `skipLocationChanges` is `true` then the url does not show it. which is fine. but i havent figured out what happens when it is `false`... Do you know? – Omar Apr 26 '18 at 22:32
  • 1
    when your query params are changed, does that reflect in the url as well? – Tisha Dec 08 '19 at 13:28
  • What if this was a google map and the latitude and longitude were to be appended to the url such that any panning action on the map by the user would also cause the query params in the url to get updated as the lat/lon would change? – Tisha Dec 08 '19 at 14:38
  • 5
    When `skipLocationChanges` is `false` URL shows the params – Isuru Feb 25 '21 at 12:43
  • I have the same requirement but a slight difference. I need to add a token to all the route urls? Can we achieve this in a generic way than adding to every router.navigate()? – Arj 1411 Dec 02 '21 at 12:45
  • I agree that the "skipLocationChange" param should be set to "false" (or just omitted), so it answers the posted question. When false, it adds the new location to the browser history. – Tony Sep 06 '22 at 14:31
41

I had to adjust Jota.Toledos answer a bit so that it works for me, I had to take out the second and the last property of the extras - object:

   navigateToFoo(){
     this._router.navigate([], {
      queryParams: {
        newOrdNum: '123'
      },
      queryParamsHandling: 'merge',
    });
   }
5

You should write

let params = new HttpParams();
params = params.append('newOrdNum','123');
Ula
  • 75
  • 1
  • 2
  • And then (how to use the newly created params variable)? Otherwise this doesn't solve/do anything, and doesn't answer the question posted. – Tony Sep 06 '22 at 13:59
3
this.router.navigate(['.'], { relativeTo: this.route, queryParams: { 'a': 'b' }, queryParamsHandling: 'merge', skipLocationChange: true});

router: Router route: ActivatedRoute

Giggs
  • 851
  • 10
  • 16
2

You should use Router module. check this doc: https://angular.io/guide/router

You need import these modules: import { Router, ActivatedRoute, ParamMap } from '@angular/router';

Salim Ibrohimi
  • 1,351
  • 3
  • 17
  • 35
1

You'll want to take the current state of the query parameters from the Angular Router, modify those props (add / delete parameters), then reassign it using the Router:

// Make sure to import and define the Angular Router and current Route in your constructor
constructor(
  private router: Router,
  private route: ActivatedRoute
) {}

...
...
...

// Take current queryParameters from the activated route snapshot
const urlParameters = Object.assign({}, this.route.snapshot.queryParams); 

// Need to delete a parameter ?
delete urlParameters.parameterName;

// Need to add or updated a parameter ?
urlParameters.parameterName = newValue;

// Update the URL with the Angular Router with your new parameters
this.router.navigate([], { relativeTo: this.route, queryParams: urlParameters });


You could even go further and build a utility function to do this:

handleUrlParameters(paramsToAdd: {param: string}[], paramsToDelete?: string[]) {
  const urlParameters = Object.assign({}, this.route.snapshot.queryParams); 

  paramsToDelete.forEach(param => delete urlParameters[param]);

  Object.keys(paramsToAdd).forEach(param => urlParameters[param] = paramsToAdd[param]);

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

And then you simply call handleUrlParameters with an object mapping a parameter to new values, or an array of parameter names to delete.

Jeff Gilliland
  • 2,782
  • 2
  • 13
  • 7
1

Make sure while passing query params value should not be undefined.

      this.router.navigate([yourRoute,
         queryParams : 
              {
                key : (yourValue ? yourValue : '')
              },
         queryParamsHandling: 'merge'
            ]);
      
Community
  • 1
  • 1