Angular http post请求总是发送一个空对象 [英] Angular http post request always sends an empty object

查看:610
本文介绍了Angular http post请求总是发送一个空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用angular来发布一些数据,当我用Postbin检查它时,我在响应中不断得到一个空对象。我在我的代码中的其他地方订阅了这个函数,所以我确定请求正在通过:

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:

使用Postman一切正常,但我看不出有什么问题使用以下代码:

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


推荐答案

我会调整一些东西:

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

为安全起见。

你确实想要JSON.stringify。我通常在没有{body:}
标题的情况下这样做。
所以你有

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

使用地图你可以做到

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

请记住,您必须订阅一个Observable才能开始。

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

订阅包括3部分:成功,错误,最后。

错误&最后是可选的。

如果只有一个语句花括号{}是可选的。

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

这篇关于Angular http post请求总是发送一个空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆