2

I'm currently using an API with functionnal tests. So I know that I'll have a good response with the url bellow :

/api/v1/investisseurs?vehicule%5B0%5D=4

Equivalent url decoded

/api/v1/investisseurs?vehicule[0]=4

Using Angular to emit my call with HttpParams like follow

getInvestors(params: HttpParams): Promise<MelodiiaCollectionResponse> {
    console.log(params);
    return <Promise<MelodiiaCollectionResponse>>this.http.get(environment.httpdBackHost + '/investisseurs', {
       params: params,
}).toPromise();

This result with the following request in my browser

/api/v1/investisseurs?vehicule%5B%5D=%5B%222%22%5D&page=1&max_per_page=15

Equivalent url decoded

/api/v1/investisseurs?vehicule[]=["2"]&page=1&max_per_page=15

Question, how it is possible to have the same query parameter encoding as the php method http_build_query within Angular 7?

I would like avoid reimplement the wheel myself :)

Thank in advance for your help

1 Answer 1

2

You can use HttpParams builder to automatically parse your params by chaining append method. And with some reducers you can provide array values in your httpParams

import { HttpParams } from '@angular/common/http';

//Whatever...

getInvestors(vehicules: number[], page: number, maxPerPage: number): Promise<MelodiiaCollectionResponse> {
  const params = vehicules.reduce(
    (previous, vehicule, index) => previous.append(`vehicule[${index}]`, vehicule.toString()),
     new HttpParams()
   )
   .append('max_per_page', maxPerPage.toString())
   .append('page', page.toString())
  return this.http.get<MelodiiaCollectionResponse>(`${environment.httpdBackHost}/investisseurs`, {
     params,
  }).toPromise();
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'll test your answer asap, and then come back to you. Thank :)
De rien mon cher ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.