0
嗨,大家好,爲什麼我的數據保存在DB兩次?如果我提交表單,表單數據將被保存,但它在db中創建另一個empety行也爲什麼?角度4 crud插入數據到MySQL數據庫與PHP
結果是這個樣子:
名 - 用戶名 - 電子郵件 - 數 - - - -
我的用戶服務
import {Injectable} from "@angular/core";
import {User} from "./user";
import {Http} from "@angular/http";
import "rxjs";
import { Observable } from "rxjs"
@Injectable()
export class UserService {
constructor(private _http: Http) {
}
create(user) {
return this._http.post('http://localhost/api/create.php', user).map(()=>"")
}
user.component.ts
import {Component, OnInit} from "@angular/core";
import {User} from "./user";
import {UserService} from "./user.service";
import {isNumber} from "util";
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
// users: Array<User> = [
// new User(1, 'fist', 'last', '[email protected]'),
// new User(2, 'second', '2last', '[email protected]'),
// new User(3, 'third', '3last', '[email protected]')
//
// ];
users: Array<User>;
constructor(private _userService: UserService) {
}
ngOnInit() {
this.getUsers();
// this.destroy();
}
create(user) {
//console.log(user);
this._userService.create(user).subscribe(() => this.getUsers())
}
destroy(id) {
this._userService.ndelete(id.id).subscribe(() => this.getUsers())
}
// update(users: any) {
// const i = this.users.indexOf(users.original);
// this.users[i] = users.edited;
//}
getUsers() {
this._userService.getUsers()
.subscribe(users => {
this.users = users
});
}
}
and here是emmit數據父
用戶new.component.ts
import {Component, OnInit, Output, EventEmitter} from '@angular/core';
import {User} from "../user";
@Component({
selector: 'app-user-new',
templateUrl: './user-new.component.html',
styleUrls: ['./user-new.component.css']
})
export class UserNewComponent implements OnInit {
newUser = new User();
@Output() createNewUserEvent = new EventEmitter();
constructor() { }
ngOnInit() {
}
create(){
this.createNewUserEvent.emit(this.newUser);
//this.newUser = new User;
}
}
我的孩子組件及其形式
<h3>user new component</h3>
<form (submit)= "create()">
<input type="text" name="name" [(ngModel)]="newUser.name">
<input type="text" name="username" [(ngModel)]="newUser.username">
<input type="text" name="email" [(ngModel)]="newUser.email">
<input type="text" name="phone" [(ngModel)]="newUser.phone">
<input type="submit">
</form>
這裏是與MySQL進行交互的PHP文件數據庫
include ("db.class.php");
$conn = new Db();
$data = json_decode(file_get_contents("php://input"));
$sql = "insert into users set
name= '$data->name',
username= '$data->username',
email= '$data->email',
phone= '$data->phone'
";
$stmt = $conn->conn->prepare($sql);
$stmt->execute();
$conn->conn = null;
//end
它發送兩個請求嗎? –