Angular: append query parameters to URL

None picture None · Sep 14, 2017 · Viewed 64k times · Source

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?

Answer

Jota.Toledo picture Jota.Toledo · Sep 14, 2017

This could be archived 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