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

6
  • 2
    this json is invalid . please check your json : jsonlint.com Commented Nov 15, 2019 at 7:43
  • sorry, I changed it, forgot to remove the coma. Now it should be valid json. Commented Nov 15, 2019 at 7: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 Commented Nov 15, 2019 at 7: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? Commented Nov 15, 2019 at 7:55
  • I tried it with Object.assign and send it as a JSON object but it is still not working.. Commented Nov 15, 2019 at 8:02

2 Answers 2

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))
}
Sign up to request clarification or add additional context in comments.

Comments

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);
}

2 Comments

@Cara please check this
Hey, thank you for your answere! I think it is a server side error. I will try it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.