Angular 4 - 编辑数据库

时间:2017-09-08 08:39:45

标签: angular

如何使用http服务从数据库更新数据。

php mysql

function updateEmployees() {
    global $con, $employeesTable;
    return $updateEmployees = mysqli_query($con, "UPDATE $employeesTable SET first_name='test', last_name ='".$request->last_name."' WHERE emp_id = '".$request->user_id."' ");
}

FORM

<p><input type="text" [(ngModel)]="first_name"></p>
<p><input type="text" [(ngModel)]="last_name"></p>
<p><input type="hidden" [(ngModel)]="user_id"></p>
<button (click)="editForm()">Edit</button>

服务

  updateEmployees(data) {
   console.log(data);
   let headers = new Headers({ 'content-type': 'application/json' }),
     options = new RequestOptions({ headers: headers });
   this.http.post('http://localhost/employees/?p=updateEmployees', data, options)
  .subscribe(data => data);
}

组件

在页面加载时,我从数据库中获取的第一个字符和最后一个字符将把数据传递给输入表单。

  ngOnInit() {
  this.activatedRoute.queryParams.subscribe((queryParams: Params) => {
    let userId = queryParams['id'];
    this.employeesServices.getEmployeesById(userId)
      .subscribe(data => {
        this.first_name = data.first_name,
        this.last_name = data.last_name,
        this.user_id = userId
      });
  });
}

然后在表格提交时,它会将更新的数据发布到数据库。 但我无法正确使用。

editForm() {
  this.myForm = new FormGroup( {
    'first_name': new FormControl(this.first_name),
    'last_name': new FormControl(this.last_name)
  } )
  this.employeesServices.updateEmployees(this.myForm.value);
}

日志显示{first_name:“input1”,last_name:“input2”}但不更新到数据库

1 个答案:

答案 0 :(得分:0)

<强> HTML

<form (ngSubmit)="update(userform)" #userform="ngForm">
<p><input name="first_name" type="text" [(ngModel)]="first_name"></p>
<p><input name="last_name" type="text" [(ngModel)]="last_name"></p>
<p><input name="user_id" type="hidden" [(ngModel)]="user_id"></p>
<button type="submit">Edit</button>
</form>

<强>组件

 update(form: NgForm) {
     console.log(form.value); // confirm value on console
     this.employeesServices.updateEmployees(form.value);
    }

您的服务应该像

updateEmployees(data) : Observable<any>{
   let headers = new Headers({ 'content-type': 'application/json' }),
     options = new RequestOptions({ headers: headers });
   const url = 'http://localhost/employees/?p=updateEmployees';
   return this.http.put(url, data, options).map(
            (res: Response) => {
                return res.json();
            }).catch(
            (error: Response) => {
                return Observable.throw(error.json() as JsonResponse);
            });
}