Angular4 ngsubmit将数据表格转换为php文件

时间:2018-01-04 10:21:01

标签: php angular

我正在尝试使用Angular4和MySQL以及PHP设置CRUD系统,为此我创建了一个服务文件tables.service.ts

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class TablesService {

constructor(private http: Http) {
}
 // get table content
getTableContent() {
return this.http.get('http://localhost/Backend/tables.php')
    .map(res => res.json()
    );
 }
// post data to table
postTableContent(contents: any[]) {
  const headers = new Headers({'Content-Type': 'application/json'});
  console.log('form data \n' + JSON.stringify(contents));
  return this.http.post('http://localhost/Backend/postData.php',
      JSON.stringify(contents),
      {headers: headers}
   );
 }
}

在我的table.ts文件中,我订阅了这项服务:

import {Component, OnInit, ViewChild, ViewEncapsulation} from 
 '@angular/core';
 import {TablesService} from '../../../services/tables.service';
 import {NgForm} from '@angular/forms';

 @Component({
 selector: 'app-table-choisie',
 templateUrl: './table-choisie.component.html',
 styleUrls: ['./table-choisie.component.css'],
 encapsulation: ViewEncapsulation.None
})
export class TableChoisieComponent implements OnInit {
 tableContents: any[];
 @ViewChild('f') signupForm: NgForm;

constructor(private tableContentsS: TablesService) { }

ngOnInit() {
// afficher le contenue d'une table
this.tableContentsS.getTableContent()
    .subscribe(
        (tableContents) => {
          console.log(tableContents);
          this.tableContents = tableContents;
        },
        (error) => console.log('Error ' + error)
    );
 }

// on submit
onSubmit(form: NgForm) {
    this.tableContentsS.postTableContent(form.value)
        .subscribe(
            (formContents) => console.log('Form Contents'+formContents),
            (error) => console.log(error)
        );
    // print form values to the console
    // console.log(JSON.stringify(form.value));
    this.signupForm.reset();
     }

  }

Get方法工作正常,但是我很难用post方法将数据发送到服务器,我搜索了很多,但我找不到正确的方法。

我的postData.php文件:

<?php   

 header('Access-Control-Allow-Origin:*');
 header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-
 Token');
 include('connexion.php');

 $data = file_get_contents("php://input");
 echo json_decode($data);
 ?>

当我提交表格时,我有这个输出: enter image description here

我真的被封锁了,我不知道如何继续

非常感谢

2 个答案:

答案 0 :(得分:0)

试试这个

postTableContent(contents: any[]) {

  let formData:FormData = new FormData();

   formData.append('data', JSON.stringify(data));

  const headers = new Headers({'Content-Type': 'application/json'});
  console.log('form data \n' + JSON.stringify(contents));
  return this.http.post('http://localhost/Backend/postData.php',formData,{headers: headers});
 }
}

并在你的php中

<?php   

 header('Access-Control-Allow-Origin:*');
 header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-
 Token');
 include('connexion.php');

 echo json_encode($_POST);
 ?>

答案 1 :(得分:0)

我把这段代码放在我的php文件中:

<?php  
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods: PUT, GET, POST, OPTIONS ");
header("Access-Control-Allow-Headers: Origin, X-Requested-Width, Content-
Type, Accept");
 //*************** */
include('connexion.php');

$data = json_decode(file_get_contents('php://input'), true);
$statement = $pdo->prepare( "INSERT INTO users (firstName, lastName) 
VALUES (:fname, :lname)");
$statement->bindParam('fname', $fname);
$statement->bindParam('lname', $lname);
$result = $statement->execute();
?>

在我的用户后文件中:

addUser(fname: string, lname: string) {
if (this.mysqlService.addMysqlUserData(fname, lname)) {
  alert('Data Inserted Successfully');
  this.mysqlService.newDataAdded.emit('yes');
}

}

并在用户后的html文件中:

<div class="form-group row">
<label class="col-sm-2" for="fname">First Name</label>
<div class="col-sm-10">
    <input type="text" class="form-control" id="fname" #fname 
     placeholder="first name">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2" for="lname">Last Name</label>
<div class="col-sm-10">
    <input type="text" class="form-control col-sm-8" id="lname" #lname 
 placeholder="last name">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
    <button class="btn btn-primary" (click)="addUser(fname.value, 
 lname.value)">Add user</button>
</div>
</div>

它工作正常。 非常感谢你的回答 关于gr