Angular2 post 到网络服务

Angular2 post to web service

constructor(platform: Platform, public http: Http) {
    this.platform = platform;
    this.headers = new Headers();
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
}



send(subject, body)
{
    var body = "subject=" + subject + "&body=" + body;

    let result = this.http.post('http://172.16.2.115:3004/message',
        body, 
        {
            headers: this.headers
        });


    console.log(body);
    console.log(this._apiUrl);

    return result;         
}

我正在尝试使用 Ionic2 和 Angular2 beta post 向 Rails 网络服务上的 Ruby 发送消息。 Web 服务工作正常,问题是离子应用程序似乎 posting 消息。 这样看起来对吗?

您需要订阅 observable 才能执行,因为 observable 是惰性的。

如果想return调用结果,可以在调用方法内订阅。不要忘记请求是异步执行的,所以你会在订阅方法指定的回调中收到响应数据。

this.service.send(asunto, cuerpo).subscribe((result) => { // <------
  // do something with the result
});

在这种情况下,send方法可以保持不变:

send(asunto, cuerpo) {
  var body = "subject=" + asunto + "&body=" + cuerpo;

  return this.http.post(this._apiUrl,
    body, {
        headers: this.headers
    }).map(res => res.json());
}

如果您对如何组织代码以与 HTTP 服务交互感兴趣,可以查看以下问题:

此外,您可以利用 URLSearchParams class 来构建您的表单内容:

let content = new URLSearchParams();
content.set('subject', asunto);
content.set('body', cuerpo);

var inputPayload = content.toString();

您需要subscribe()否则将不会发送任何请求

send(subject, body)
{
    var body = "subject=" + subject + "&body=" + body;

    let result = this.http.post('http://172.16.2.115:3004/message',
        body, 
        {
            headers: this.headers
        })
    .subscribe(res => {
      this.comments = res.json();
      console.log(body);
      console.log(this._apiUrl);

      // no effect here
      // return result;             
    });  
}

您需要将处理响应的代码移动到 subscribe() 中,否则它会在响应到达之前执行。 你不能 return 结果,你只能 return 可观察的供其他人订阅。

send(subject, body)
{
    var body = "subject=" + subject + "&body=" + body;

    return this.http.post('http://172.16.2.115:3004/message',
        body, 
        {
            headers: this.headers
        });
    .map(res => {
      this.comments = res.json();
    });  
}
this.send.subscribe(res => {
   console.log(body);
   console.log(this._apiUrl);
});