Angular 7: Add multiple parameters to the URL with Httpparams

Asked

Viewed 248 times

0

Reading the angular documentation I managed to develop the following search method with filters, but the problem is that I need a search with several filters and not just 1 as shows the code below developed by me. I tried several ways but did not succeed in adding several parameters to the URL...

consultar(filtro: PacienteFiltro): Promise<any> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'Basic ' + btoa('admin' + ':' + 'admin')
      }),
      params: filtro.nome ? new HttpParams().set('nome', filtro.nome) : {}
    };

    return this.http.get(this.url, httpOptions)
      .toPromise()
      .then(response => response);
}

1 answer

1


You can do the following:

Create httpOptions object normally without params:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa('admin' + ':' + 'admin')
  })
}

Then perform the following parameter setting (This step will link the parameters to the header):

const requestOptions = Object.assign({}, httpOptions);

requestOptions['params'] = Object.assign({}, filtro);

The code will look like this:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa('admin' + ':' + 'admin')
  })
};

const requestOptions = Object.assign({}, httpOptions);

requestOptions['params'] = Object.assign({}, filtro);

return this.http.get(this.url, requestOptions)
    .toPromise()
    .then(response => response);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.