我是angular的初学者,我试图使用php作为后端编程语言与数据库建立连接,它工作正常,并且元素从数据库中显示出来,但是当我将它们插入数据库时,它确实可以工作并将它们插入数据库中,但是当提交表单时,我的元素消失了;当再次提交表单时,它们闪烁了几秒钟。
我的HTML代码
<form (submit)="loginUser($event)">
<input type="text" placeholder="User name" id="name" >
<input type="password" placeholder="password" id="pass">
<button type="submit" >Log in</button>
{{name}}
</form>
<ul *ngFor="let item of datas ">
<li>{{item.name}} {{item.pass}}</li>
</ul>
我的登录名.COMPONENT文件
import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { iEmployee } from '../../empolyee';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor( private Auth:AuthService) { }
public datas;
ngOnInit() {
this.Auth.getUserDetail().subscribe(data=> this.datas=data);
}
loginUser(event: { preventDefault: () => void; target: any; }){
event.preventDefault();
const target = event.target;
const name=target.querySelector('#name').value;
const pass=target.querySelector('#pass').value;
this.Auth.createuser(name,pass).subscribe(data=>this.datas=data);
this.Auth.getUserDetail().subscribe(data=> this.datas=data);
}
}
我的授权服务文件
import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { iEmployee } from '../empolyee';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http:HttpClient) { }
private url : string='http://localhost:81/example/Angular/php/display.php';
private url2:string='http://localhost:81/example/Angular/php/addNew.php';
getUserDetail() {
return this.http.get(this.url)
}
createuser(name , pass) {
return this.http.post(this.url2,{name,pass},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
}
}
我的ADDNEW.PHP文件
<?php
header('Access-Control-Allow-Origin: *');
include 'connection.php';
$data = json_decode(file_get_contents("php://input"),true);
$name= $data['name'];
$pass= $data['pass'];
$sql="insert into test(name,pass) values ('$name','$pass')";
$result = mysqli_query($con, $sql);
?>