0

I'm having trouble finding guidance on the best-practice way to do this with angular (2+). Angular's HttpClient's post function has an HttpParams parameter. HttpParams is a key/value map of type [param: string]: string | string[]. But, I need to post a multidimensional array (2D) parameter (string[][]). i.e.

this.http.post(url, {}, {
    params: {
        2d: [ [ 'arr1' ], [ 'arr2' ] ]
    }
});

But this does not seem to be supported by angular's HttpParams class. While searching around other questions, I found out that

I'm wondering if there is a clean way to do this in angular. If there is not, why did angular make this design decision and what is a workaround?

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Corey Cole
  • 2,262
  • 1
  • 26
  • 43

2 Answers2

1

Can you just send it as a json array?

let data= [
    ["string1","string2"],
    ["string3", "string4"]
 ];


let body= {
 content: data
};

this.http.post(url, body)
David
  • 33,444
  • 11
  • 80
  • 118
0

Thanks to @Jota.Toledo, @David and this question on "Is there any difference between using request.body or request.params", my main misunderstanding was trying to use HttpParams for everything and ignoring the request body. The best solution to my problem is to simply pass the multidimensional array in the request body.

This is the "best-practice" way for a few reasons

  • The request body doesn't have any restrictions on the complexity of the data (type "any" in the angular docs)
  • Using the body doesn't encode the data in the url, this avoids a potential status 414 (Request-URI Too Long) if too much data is passed
  • Following a RESTful pattern, you generally use params for GET requests and the body for POST requests (Stack Overflow question source)
Corey Cole
  • 2,262
  • 1
  • 26
  • 43