73

I dont know how to make an API call to such a method:

[HttpGet]
[ActionName("GetSupport")]
public HttpResponseMessage GetSupport(int projectid)

Because it is GET but still got a parameter to pass, how to do this? Would it be something like this?

let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      headers.append('projectid', this.id);

      this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers })
shammelburg
  • 6,974
  • 7
  • 26
  • 34
  • 3
    Possible duplicate of [How to pass url arguments (query string) to a HTTP request on Angular 2](https://stackoverflow.com/questions/34475523/how-to-pass-url-arguments-query-string-to-a-http-request-on-angular-2) – anoop May 31 '17 at 09:11

5 Answers5

139

Having something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('projectid', this.id);
let params = new URLSearchParams();
params.append("someParamKey", this.someParamValue)

this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers, search: params })

Of course, appending every param you need to params. It gives you a lot more flexibility than just using a URL string to pass params to the request.

EDIT(28.09.2017): As Al-Mothafar stated in a comment, search is deprecated as of Angular 4, so you should use params

EDIT(02.11.2017): If you are using the new HttpClient there are now HttpParams, which look and are used like this:

let params = new HttpParams().set("paramName",paramValue).set("paramName2", paramValue2); //Create new HttpParams

And then add the params to the request in, basically, the same way:

this.http.get(url, {headers: headers, params: params}); 
//No need to use .map(res => res.json()) anymore

More in the docs for HttpParams and HttpClient

spottedmahn
  • 14,823
  • 13
  • 108
  • 178
DGarvanski
  • 2,555
  • 3
  • 26
  • 35
  • 10
    `search` deprecated for angular 4, use `params` instead – Al-Mothafar Sep 26 '17 at 14:09
  • 10
    Keep in mind that `params.set("key", value)` doesn't update the original params-object, so you need to reassign it: `params = params.set("key", value)` unless you chain them like in the answer – baltzar Nov 29 '19 at 15:06
  • @BaltzarMattson Thank you so much for mentioning this! I would have wasted a few hours otherwise. – olfek Feb 02 '20 at 19:23
  • To put @BaltzarMattson 's answer in a more "computer-sciency" way is that `set` is a non-mutating method of `params`. (A number of programmers in general need to learn the difference between mutating and non-mutating and its significance -- my 2¢) – Greg Feb 03 '20 at 22:11
  • the set method doesn't update the value, which is counterintuitive and which made me waste time Thanks @baltzar – ColdFire Sep 30 '21 at 16:55
22

For Angular 9+ You can add headers and params directly without the key-value notion:

const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params}); 
Yassir Khaldi
  • 1,452
  • 1
  • 17
  • 30
3

Above solutions not helped me, but I resolve same issue by next way

private setHeaders(params) {      
        const accessToken = this.localStorageService.get('token');
        const reqData = {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        };
        if(params) {
            let reqParams = {};        
            Object.keys(params).map(k =>{
                reqParams[k] = params[k];
            });
            reqData['params'] = reqParams;
        }
        return reqData;
    }

and send request

this.http.get(this.getUrl(url), this.setHeaders(params))

Its work with NestJS backend, with other I don't know.

V.Tur
  • 1,115
  • 9
  • 20
3

Just offering up a helpful piece of code for anyone interested in the HttpParams direction mentioned in the answer from 2017.

Here is my go-to api.service which kind of "automates" params into that HttpParams for requests.

import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Params } from '@angular/router';
import { Observable } from 'rxjs';
import { environment } from '@env';

@Injectable({
    providedIn: 'root'
})
export class ApiService {

    constructor(private http: HttpClient) { }

    public get<T>(path: string, routerParams?: Params): Observable<T> {
        let queryParams: Params = {};
        if (routerParams) {
            queryParams = this.setParameter(routerParams);
        }
        console.log(queryParams);
        return this.http.get<T>(this.path(path), { params: queryParams });
    }

    public put<T>(path: string, body: Record<string, any> = {}): Observable<any> {
        return this.http.put(this.path(path), body);
    }

    public post<T>(path: string, body: Record<string, any> = {}): Observable<any> {
        return this.http.post(this.path(path), body);
    }

    public delete<T>(path: string): Observable<any> {
        return this.http.delete(this.path(path));
    }

    private setParameter(routerParams: Params): HttpParams {
        let queryParams = new HttpParams();
        for (const key in routerParams) {
            if (routerParams.hasOwnProperty(key)) {
                queryParams = queryParams.set(key, routerParams[key]);
            }
        }
        return queryParams;
    }

    private path(path: string): string {
        return `${environment.api_url}${path}`;
    }
}
Ben Racicot
  • 5,332
  • 12
  • 66
  • 130
2

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   }
   
   return parts.join('&');
}
Malik Haseeb
  • 471
  • 9
  • 20