2017-01-09 15 views
0

私はニュースフィードを表示するモバイルアプリを構築しています。私のアプリでは、ステータスを投稿できるはずです。Angular2 - サーバーにPOSTリクエストを送信

ステータスはPOSTメソッドを使用してPHPサーバーに送信されます。

私の問題は、私がangle2を使用して送信したPOST要求を読み取ることができないことです。

これは私のコードです:

form.html

<form class="sample-form post-form" [formGroup]="post_form" (ngSubmit)="createStatus()"> 
      <ion-item> 
       <ion-textarea rows="7" placeholder="What's happening?'" formControlName="status"></ion-textarea> 
      </ion-item> 
      <section class="form-section"> 
       <button ion-button block class="form-action-button create-post-button" type="submit" [disabled]="!post_form.valid">Post</button> 
      </section> 
      </form> 

form.ts

import { Component } from '@angular/core'; 
import { NavController, AlertController } from 'ionic-angular'; 
import { Validators, FormGroup, FormControl } from '@angular/forms'; 

import { Http, Headers } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Component({ 
    selector: 'form-page', 
    templateUrl: 'form.html' 
}) 
export class FormLayoutPage { 

    section: string; 

    post_form: any; 

    url: string; 
    headers: Headers; 

    constructor(public nav: NavController, public alertCtrl: AlertController, public http: Http) { 
    this.headers = new Headers(); 
    this.headers.append("Content-Type", "application/x-www-form-urlencoded"); 

    this.section = "post"; 


    this.post_form = new FormGroup({ 
     status: new FormControl('', Validators.required), 
    }); 
    } 

    createStatus(){ 
    console.log(this.post_form.value); 

    this.url = "https://domain.com/mobileREST/poststatus.php"; 

    this.http.post(this.url, this.post_form.value, { headers: this.headers}) 
     .map(res => res.json()) 
     .subscribe(res => { 
     console.log(res); 
     }, 
     err => { 
     console.log(err); 
     }) 
    } 
} 

poststatus.php

<?php 
header('Access-Control-Allow-Origin: *'); 
header('Content-Type: application/json'); 

$status = $_POST["status"]; 
echo json_encode($status); 
?> 

Firebugのコンソール: enter image description here

ここではエラーが見つからないようです。あなたの助けに本当に感謝します。

答えて

6

私は同じ問題を抱えていました。あなたは、javascriptオブジェクトのようなPOSTパラメータを送ることはできません。 URLSearchParamsのように渡す必要があります。私はあなたのためにそれを行う機能を作った。オブジェクトをループしてURLSearchParamを作成し、文字列として返します。

this._http.post(this.url, this._buildParams(params), {headers: this.headers}); 
+0

こんにちは、ここに新しい角度のユーザーにこの行を追加取得するには:

private _buildParams(params: any) { let urlSearchParams = new URLSearchParams(); for(let key in params){ if(params.hasOwnProperty(key)){ urlSearchParams.append(key, params[key]); } } return urlSearchParams.toString(); } 

そして、その後、あなたは、httpポストを呼び出します。 private変数に_を使用した理由を説明できますか? _httpと_buildParamsの両方に必要ですか? – iWillGetBetter

+0

@iWillGetBetterこれは必須ではありませんが、プライベートメソッドと変数に使用される単なる慣習です。 –

0

がポストされたデータは、ちょうどあなたのPHPファイル

// get posted data 
$data = json_decode(file_get_contents("php://input")); 
関連する問題