Angular http post request always sends an empty ob

2020-03-31 08:30发布

问题:

I'm trying to POST some data using angular and I keep getting an empty object on the response when I inspect it with Postbin. I subscribe to this function elsewhere in my code so I'm sure the request is going through:

Everything works fine using Postman, but I can't see what is wrong with the code below:

postRequest(order): Observable<any> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    const data = {
      "data": {
        "ID": "1",
        "Name": "John",
        "Class": "Adventurer",
        "Items": [
          "641",
          "642",
          "643",
          "513",
          "512"
        ]
      }
    }
    return this.http.post('https://requestb.in/wjoscywj', { body: JSON.stringify(data) }, { headers: headers })
      .map(this.extractData)
      .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

回答1:

I would tweak a few things:

 headers.append('Content-Type', 'application/json; charset=utf-8');

to be on safe side.

You do want JSON.stringify. I normally do it without {body: } same for headers. so you have

this.http.post('https://requestb.in/wjoscywj', JSON.stringify(data), headers);

With the map you can just do

map((resp:Response) => resp.json()) 

Remember you have to subscribe to an Observable to start things going.

In your case I would tend to have the service with signature:

postRequest(order): Observable<Response> {
   //setup headers and do post here
}

That way you still have type safety at the method level.

Then, in the calling function do the map and subscribe like so:

this.postRequest(order)
  .map((resp:Response) => resp.json())
  .subscribe(data =>  { console.log(data);
                        this.data = data;
                      },
             error => { console.error(error)
                      },
             ()    => { // Finally
                      }
   )

Subscribe consists of 3 parts: Success, Error, Finally.
Error & Finally are optional.
If only 1 statement curly braces {} are optional.



标签: angular http