这是我的home.component.html,其中我已经放了所有的HTML
<div style="margin-left:25%;padding:1px 16px;height:1000px;">
<h2>Add Users</h2>
<form action="empRegister.php" method="POST" (ngSubmit)="onSubmit()">
<div>
<label>Full Name</label>
<input type="text" name="emp_name" ngControl="emp_name">
</div>
<input type="submit" name="submit">
</form>
</div>
这是我的home.component.ts文件,另一个文件是home.module.ts和routes.ts
import { Component } from '@angular/core';
import {ContactService} from './contact.service';
@Component({
moduleId: module.id,
selector: 'home-cmp',
templateUrl: 'home.component.html',
providers : [ContactService]
})
export class HomeComponent {
constructor(private _contactService : ContactService) { }
public message: Insert = {emp_name: ''};
onSubmit() {
this._contactService.postInsert(this.message).subscribe(
response => this.handleResponse(response),
error => this.handleResponse(error)
);
}
handleResponse(response){
console.log(`msg is: {response.status}`);
if(response.status =='success'){
this.message = {emp_name: ''};
alert('success');
}
if(response.status =='error'){
alert('error');
}
}
}
interface Insert
{
emp_name:string;
}
这是contact.service.ts文件
import {Injectable} from '@angular/core';
import {Http,Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable()
export class ContactService {
constructor (private _http: Http) {}
private _contactUrl =
'http://localhost/proj2/src/databaseFiles/empRegister.php';
postInsert(newinsert: Insert): Observable<string>{
let body = `emp_name=${newinsert.emp_name}`;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-
urlencoded' });
let options = new RequestOptions({ headers: headers });
return this._http.post(this._contactUrl, body, options)
.map(res => <string> res.json())
.catch(this.handleError)
}
private handleError (error: Response) {
console.error('Error in retrieving : ' + error);
return Observable.throw(error.json().error || 'Server error');
}
}
对于数据插入empRegister.php
<?php
require_once 'database_connections.php';
$emp_name = $_POST['emp_name'];
$sql = "INSERT INTO emp_details (emp_name)
VALUES ('$emp_name')";
if (mysqli_query($con, $sql)) {
$response_array['status'] = 'success';
echo json_encode($response_array);
} else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
?>
所以,这是我在mysql数据库中插入数据的完整过程。但是数据没有插入表格
答案 0 :(得分:1)
从表单中删除以下内容:
action="empRegister.php" method="POST"
因为您使用onSubmit
- 函数处理请求。然后我在你的请求中看到了一些问题。尝试使用URLSearchParams
:
import { URLSearchParams } from '@angular/http';
postInsert(newinsert: Insert): Observable<string>{
let body = new URLSearchParams();
body.set('emp_name', newinsert.emp_name)
let headers = new Headers({ 'Content-Type':'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers });
return this._http.post(this._contactUrl, body, options)
.map(res => res.json())
.catch(this.handleError)
}