Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 http.get with params

I want to send query parameters within a GET request. My class looks like this:

 @Injectable()
 export class Loader implements TranslateLoader{
  constructor(private http: Http){
   }
   getTranslation(lang: string): Observable<any>
   {
     return this.http.get(routes.Localization.Get) ;// in that place I need to pass params
   }
 }

How can I do this?

like image 425
Sveta Antrapovich Avatar asked Jul 20 '16 08:07

Sveta Antrapovich


1 Answers

You can leverage the URLSearchParams class for this:

getTranslation(lang: string): Observable<any> {
  let params = new URLSearchParams();
  params.set('param1', 'value1');

  return this.http.get(routes.Localization.Get, { search: params });
}

This will result to an URL like this (parameters are added in the query string): http://...?param1=value1.

See the documentation of this class:

  • https://angular.io/docs/ts/latest/api/http/index/URLSearchParams-class.html

It now providers support for encoding / decoding parameters.

like image 115
Thierry Templier Avatar answered Oct 02 '22 14:10

Thierry Templier