Home > Net >  How do I construct params for a get request?
How do I construct params for a get request?

Time:08-18

I am trying to do:

export interface ApiCallOptions {
  abc: string,
  xyz: number
}
makeRequest (options: ApiCallOptions) {
  return this.http.get('/some/path/to/endpoint', { params: options });
}

I get an error that ApiCallOptions isn't a HttpParams object... I tried casting options as HttpParams, still fails..

So then I tried:

  const params = new HttpParams({ fromObject: options });
  return this.http.get('/some/path/to/endpoint', { params: params });

And I get:

The expected type comes from property 'fromObject' which is declared here on type 'HttpParamsOptions'

What am I doing wrong?

CodePudding user response:

You could do something like that:

makeRequest (options: ApiCallOptions) {
  return this.http.get('/some/path/to/endpoint', { params: this.buildParams(options) });
}

private buildParams(params) {
  let httpParams = new HttpParams();
  let keys = Object.keys(params);
  keys.forEach(key => {
    if (params[key] !== null) {
      httpParams = httpParams.append(key, params[key]);
    }
  });
  return httpParams;
}

What is the outcome?

CodePudding user response:

From HttpParamsOptions

export interface HttpParamsOptions {
  /**
   * String representation of the HTTP parameters in URL-query-string format.
   * Mutually exclusive with `fromObject`.
   */
  fromString?: string;

  /** Object map of the HTTP parameters. Mutually exclusive with `fromString`. */
  fromObject?: {[param: string]: string|number|boolean|ReadonlyArray<string|number|boolean>};

  /** Encoding codec used to parse and serialize the parameters. */
  encoder?: HttpParameterCodec;
}

For the fromObject property, it implements the index signature with property name as string.


Modify the ApiCallOptions interface as:

export interface ApiCallOptions {
  abc: string,
  xyz: number
  [key: string]: any;
}

And for the HttpParams instance:

import {
  HttpParamsOptions,
} from '@angular/common/http';

const params = new HttpParams({ fromObject: options } as HttpParamsOptions);
  • Related