Angular HttpClient Get method with body Angular HttpClient Get method with body angular angular

Angular HttpClient Get method with body


As far as I can tell you cannot use HttpClient get to send a body. You could use the query at least for it to be idiomatic. (Or you can try to force the issue somehow).

Lets say you have an array with your criteria:

const criteria = [ {a: 25}, {b: 23} ];http.get(url + '/?criteria='+ encodeURIComponent( JSON.stringify(criteria)));

Sending a body in a GET request is a violation of some RFC standard, and even though it might work you're bound to summon some arcane demons.


In the service method, you can have your method like below which takes the optional parameters for the search query. And you can send your search parameter over Observe as below.

getAllSubscribers(    page?,    itemsPerPage?,    userParams?  ): Observable<PaginatedResult<Subscribers[]>> {    const paginatedResult: PaginatedResultSubscribers[]> = new PaginatedResult<      Subscribers[]    >();    let params = new HttpParams();    if (page != null && itemsPerPage != null) {      params = params.append("pageNumber", page);      params = params.append("pageSize", itemsPerPage);    }    if (userParams != null) {      params = params.append("minAge", userParams.minAge);      params = params.append("maxAge", userParams.maxAge);        }       return this.http      .get<Subscribers[]>(this.baseUrl + "/subscribers", { observe: "response", params })      .pipe(        map(response => {          paginatedResult.result = response.body;          if (response.headers.get("Pagination") != null) {            paginatedResult.pagination = JSON.parse(              response.headers.get("Pagination")            );          }          return paginatedResult;        })      );  }

The basic idea is the use of HttpParams.


To make Amir's answer some more generic I have done the following to build params for the passed item.

To my generic data service I have added this variant:

// Get data for passed parameters or item containing filterspublic getByItem<T>(apiMethod: string, item?: T, apiParms?: HttpParams): Observable<T> {    if (!apiParms) apiParms = new HttpParams();    if (item) {        const keys = Object.keys(item) as Array<keyof T>;        for (let key of keys) {            apiParms = apiParms.append(key.toString(), item[key].toString());        }    }    // Call generic method of data service    return this.get<T>(apiMethod, apiParms); // => return this.http.get<T>(environment.apiUrl + apiMethod, { headers: this.defaultHeaders