2016-05-02 34 views
2
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ベータ版を使用してRuby on Rails Webサービスにメッセージを投稿しようとしています。 ウェブサービスは正常に機能しますが、問題はイオンアプリがメッセージを投稿しているようです。 これは正しく見えますか?Angular2 Webサービスへの投稿

答えて

3

あなたがsubscribe()する必要がありそうでなければ要求はあなたがsubscribe()にrepsonseを処理するコードを移動する必要が

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

を送信されませんそれ以外の場合は、応答が到着する前に実行されます。 結果を返すことはできません。あなたは他の誰かが視聴するために観測可能なものだけを返すことができます。

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

http://stackoverflow.com/questions/34515173/angular-2-http-get-with-typescript-error-http-get-map-is-not-a-function -in –

+0

だから、どのコードを最初のものか最後のものを使うべきですか? – Jon

+0

を投稿したことは、あなたが達成したいことに依存します;-)。このコードがサービスに含まれていて、コンポーネントまたは別のサービスで結果を取得する場合は、2番目の方が適しています。 'send()'メソッドも入っているサービスに値を格納したいだけなら、最初のものを使うこともできます。両方のケースでうまくいくので、第2は通常あなたが望むものだと思います。 –

0

observableが怠けているため、observableを購読して実行する必要があります。

結果を呼び出し元に返す場合は、呼び出し元のメソッド内でサブスクライブすることができます。要求が非同期に実行されることを忘れないでください。そうすれば、subscribeメソッドで指定されたコールバックで応答データを受信します。この場合

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サービスと対話するようにコードを整理する方法に興味があるなら、あなたが見ている可能性がありこの質問:

また、あなたのフォームの内容をbuldするURLSearchParamsクラスを活用できます。

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

var inputPayload = content.toString(); 
関連する問題