Angular 5: Is there anything like $httpParamSerailizer that was available in AngularJS?

927 views Asked by At

I am trying to serialize object to query parameters. In AngularJS I use $httpParamSerializer.

What is available in Angular 5?

1

There are 1 answers

1
R. Richards On BEST ANSWER

Here is my take on your question. This uses the HttpParamsOptions and HttpParams. The HttpParamsOptions will build out the params by passing it an object in the fromObject property. You can see in the comment what that looks like when the API call is made.

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { HttpParamsOptions } from '@angular/common/http/src/params';

@Injectable()
export class ApiService {
  constructor(private httpClient: HttpClient) { }

  getThingsWithParams(): any { // you could pass your object in as a function parameter
      const myObject: any = { this: 'thisThing', that: 'thatThing', other: 'otherThing'};
      const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
      const options = { params: new HttpParams(httpParams) };
      return this.httpClient.get<any>('http://localhost:34479/api/products/168', options);
      // This is what is sent to the API:
      // http://localhost:34479/api/products/168?this=thisThing&that=thatThing&other=otherThing
  }
}

I think this is what you are after. A way to have the parameters build based on the properties of an object.

https://github.com/angular/angular/blob/530b824faa29460a87c2401bc61d22a7fb56f939/packages/common/http/src/params.ts#L76