None
None

Reputation: 9247

Angular: append query parameters to URL

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?

Upvotes: 72

Views: 155466

Answers (6)

Jota.Toledo
Jota.Toledo

Reputation: 28464

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

Upvotes: 124

Giggs
Giggs

Reputation: 1049

this.router.navigate(['.'], { relativeTo: this.route, queryParams: { 'a': 'b' }, queryParamsHandling: 'merge', skipLocationChange: true});

router: Router route: ActivatedRoute

Upvotes: 3

Ula
Ula

Reputation: 85

You should write

let params = new HttpParams();
params = params.append('newOrdNum','123');

Upvotes: 6

Bharat chaudhari
Bharat chaudhari

Reputation: 534

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

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

Upvotes: 1

Jan Clemens Stoffregen
Jan Clemens Stoffregen

Reputation: 887

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',
    });
   }

Upvotes: 42

Salim Ibrohimi
Salim Ibrohimi

Reputation: 1391

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';

Upvotes: 2

Related Questions