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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. I try this: gyazo.com/d84e2f55d3df86030aa5ed01b0f99a0c but I have null value in my server controller gyazo.com/bf675ca73b88c858afb39982aa105a99
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...
Any guess why my .set function would fail? It looks like it's not altering the URLSearchParams object at all.
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 });

2 Comments

Remember to add this line at top: import { URLSearchParams } from '@angular/http';
this bugger had me!
-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"];
    }
}

3 Comments

This question is very old. It also asks how to SET params, not how to read them.
Sorry, The title is "Angular 2 http.get with params". I've only focused on the title (only GET without SET). If have any missing pls forget it.
the question refers to setting parameters for a http.get request

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.