0

I am not sure whether my function is wrong, which should send data to the server, or the function on the server is wrong. I looked up similar questions but the solution I adopted to my problem did not work.

My function looks like this:

postData(number){
   let array = JSON.stringify(this.locArr);
   return this.http.post<any>(this.url, array)
    .subscribe(),
    error => console.log("Error: ", error)
    }

JSON which is send:

[ 
  { 
      "id":222,
      "name":"Lars",
      "sLA":37
   },
  { 
      "id":223,
      "name":"Sim",
      "sLA":12
   }
]

All parameters like token etc. are received by the server function but the array I wrote above is null, although it is valid json. I wonder why this error is occuring.

Any advice is appreciated

Cara
  • 165
  • 1
  • 4
  • 15
  • 2
    this json is invalid . please check your json : https://jsonlint.com/ – Joel Joseph Nov 15 '19 at 07:43
  • sorry, I changed it, forgot to remove the coma. Now it should be valid json. – Cara Nov 15 '19 at 07:45
  • also you are posting an array to the server which is not valid json or more like text. you should be posting it as json object – Joel Joseph Nov 15 '19 at 07:49
  • I am not sure what you mean. The array above is valid json? I checked it with a validator, or do you mean something else? – Cara Nov 15 '19 at 07:55
  • I tried it with Object.assign and send it as a JSON object but it is still not working.. – Cara Nov 15 '19 at 08:02
  • i believe you are using httpClientModule so then there is no need of this step `JSON.stringify(this.locArr);` you neen't JSON.stringify : for more details please check : https://stackoverflow.com/questions/48921063/how-to-sent-array-data-as-formdata-angular-4 – Joel Joseph Nov 15 '19 at 08:05

2 Answers2

0

The local array will be converted into JSON automatically by Angular, you need not stringify or parse it.

postData(number){
    this.http.post<any>(this.url, this.locArr)
    .subscribe((data)=>{
        //code after receiving data from server
    },
        error => console.log("Error: ", error))
}
Morsh
  • 171
  • 2
  • 5
0

I believe you are using httpClientModule so then there is no need of tyou need't JSON.stringify remove this step JSON.stringify(this.locArr);
Also you need to send it as json object {} not json array []

postData($locArr){ // pass the array to the service function
   let data = { data : $locArr}; // note that you have to post it as json object {} not []
   return this.http.post<any>(this.url,data);
}
Joel Joseph
  • 5,889
  • 4
  • 31
  • 36