簡體   English   中英

Angular2發布到Web服務

[英]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將消息發布到Ruby on Rails Web服務。 Web服務工作正常,問題是Ionic應用似乎沒有發布消息。 這看起來正確嗎?

您需要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()否則它將在響應到達之前執行。 您無法返回結果,只能返回可觀察的結果,以供其他人訂閱。

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

由於可觀察對象是惰性的,因此您需要訂閱可觀察對象以使其執行。

如果要將結果返回給調用方,則可以在調用方法中進行預訂。 不要忘記該請求是異步執行的,因此您將在subscription方法中指定的回調中接收響應數據。

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類來獲取表單內容:

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

var inputPayload = content.toString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM