14

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?

Sveta Antrapovich
  • 407
  • 2
  • 7
  • 17
  • 2
    Possible duplicate of [How to pass url arguments (query string) to a HTTP request on Angular 2](http://stackoverflow.com/questions/34475523/how-to-pass-url-arguments-query-string-to-a-http-request-on-angular-2) – Nitzan Tomer Jul 20 '16 at 08:17

3 Answers3

41

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:

It now providers support for encoding / decoding parameters.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Thanks a lot. I try this: https://gyazo.com/d84e2f55d3df86030aa5ed01b0f99a0c but I have null value in my server controller https://gyazo.com/bf675ca73b88c858afb39982aa105a99 – Sveta Antrapovich Jul 20 '16 at 08:55
  • You're welcome! It seems that you try to get your params from payload and not from query string. Whereas it's not forbidden for GET requests, it's better to leverage the query string... – Thierry Templier Jul 20 '16 at 09:33
  • 1
    Any guess why my .set function would fail? It looks like it's not altering the URLSearchParams object at all. – ThePartyTurtle Jul 20 '17 at 22:47
12

This is pretty simple - you can define your URLSearchParams and pass them in the second parameter of the http.get method:

import { URLSearchParams } from '@angular/http'

let params: URLSearchParams = new URLSearchParams();
params.set('param1', 'someValue');
params.set('param2', 'someValue');

return this.http.get(routes.Localization.Get, { search: params });
Jobin
  • 5,610
  • 5
  • 38
  • 53
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
-8

When an URL like this http://stackoverflow.com?param1=value

You can get the param1 by code follow:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
    selector: '',
    templateUrl: './abc.html',
    styleUrls: ['./abc.less']
})
export class AbcComponent implements OnInit {
    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        // get param
        let param1 = this.route.snapshot.queryParams["param1"];
    }
}
Trung
  • 1,819
  • 1
  • 13
  • 10