0
votes

I am using HttpClient from '@angular/common/http' and wanted to perform put operation.

My Angular code is like :

public updateDetails(data: Data) {


    const url = '/project/rest/v1/configuration/device/update'
    console.log(JSON.stringify(data));
    let headers = new HttpHeaders();
     headers.append('Content-Type' , 'application/json');


    let body = JSON.stringify(data);

    return this.http.put(url, data, { headers: headers })
      .map(response => true)
      .catch(err => {
        console.log(err);
        return Observable.of(false);
      });

  }

But, i am getting

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request",

Please help me what i am missing. I tried to pass the data in stringfy format but that is also giving me same error.

2
Wait - the headers weren't there a minute ago! So the error exists with the headers? - Randy Casburn
HTTP Status 400 is quite generic and is reliant on the server configuration. This has to do with the server equally. Need to know server configuration and expectations. - Randy Casburn
@RandyCasburn i think i got the issue i am working on it. - Rohitesh
You should just send the data object and let Angular serialize it for you. Don't JSON.stringify() it first. - Randy Casburn
@RandyCasburn is right, let Angular serialize the data for you. Also, add an "Accept" header with the expected media type. I have seen that sometimes incorrect headers and url also results in HTTP 400. - Avinash Sagar

2 Answers

2
votes

It looks like you have two issues.

  1. headers.append does not modify the headers object, it returns a new headers object with the header appended.

So, instead of

let headers = new HttpHeaders();
headers.append('Content-Type' , 'application/json');

you should do

const headers = new HttpHeaders()
   .append('Content-Type' , 'application/json');

  1. You don't need to stringify the data -

just pass the object to the HttpClient, as in:

this.http.put(url, data, { headers: headers })
0
votes

try

const headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });

return this.http.put(url, data, options)