user8845321
user8845321

Reputation: 121

HTTP Query Parameters

If I have an array of the object where I'm storing all the search filters selected by a user and here is its structure:

export const filterDataObject = [{
    date: '',
    tid: '',
    className: '',
    userName: '',
    category: [],
    limit: '50',
    sort: 'acs'
}];

the REST call should be for example something like that :

   http://localhost:1234/api/query? 
_filter=tid%3Dcdfg&_limit=50&_sort=asc

while _filter is collecting all params but limit and sort

How can I pass the result array as params to my httpClient rest request especially the category array ?

Upvotes: 0

Views: 5903

Answers (2)

David
David

Reputation: 34465

I'm assuming here that you only want to send one filter to your API, not the array, and also that you are using angular 4+

Option #1

this.http.get('http://localhost:1234/api/query', {params: filterDataObject[0]})...

Option #2

You can use HttpParams

import {HttpParams} from '@angular/common/http';
//...
let params = new HttpParams();

for(let key of Object.keys(filterDataObject[0])){
    params= params.set(key, filterDataObject[0][key]) ;
}

this.http.get('http://localhost:1234/api/query', {params: params})...

Option #3

You could also try using URLSearchParams (if you do not need IE support).

let sp = new URLSearchParams();

for(let key of Object.keys(filterDataObject[0])){
    sp.set(key, filterDataObject[0][key]) 
}

const url = `http://localhost:1234/api/query?${sp.toString()}`;
this.http.get(url)...

Upvotes: 1

Chanaka Weerasinghe
Chanaka Weerasinghe

Reputation: 5742

Append data to URLSearchParams

const params = new URLSearchParams();
    params.set('sort', val);
    params.set('tid', val);
    params.set('limit', val);
    params.set('sort', val);

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      params: params,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, data, options)
      .map(this.handleData)
      .catch(this.handleError);

Upvotes: 0

Related Questions