为什么我在Angular中收到HttpErrorResponse错误?

时间:2019-02-21 11:32:18

标签: php angular6

我正在尝试将我的register.component.ts页面上的http发布请求发送到register_insert.php页面。但是我收到HttpErrorResponse错误。我在哪里做错了?请帮助

register.component.ts

  insertData() {
      this.httpClient.post(
          "http://localhost/register_insert.php",
          {
              'fullname':this.fullname, 
              'email':this.email,
              'role':this.role,
              'typee':this.typee,
              'password':this.password,

          },   
      ).subscribe((data) => {
          alert("inserted");
          console.log(data);
          this.fullname = null;
          this.email = null;
          this.role = null;
          this.typee = null;
          this.password = null;
      }, 
      (err)=>{
        console.log(err);
    });
  }

register_insert.php

    <?php  

        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH, POST, DELETE, OPTIONS");
        header('Access-Control-Max-Age: 86400');
        header("Access-Control-Expose-Headers: Content-Length, X-JSON");
        header("Access-Control-Allow-Headers: *");

include 'dbcon.php';

$data = json_decode(file_get_contents("php://input"),true);
if(count($data) > 0 ) {

    $fullname = mysqli_real_escape_string($connect,$data['fullname']);
    $email = mysqli_real_escape_string($connect, $data['email']);
    $role = mysqli_real_escape_string($connect,$data['role']);
    $type = mysqli_real_escape_string($connect, $data['typee']);
    $password = mysqli_real_escape_string($connect,$data['password']);



    $insert = "INSERT INTO tbl_user values ('','$fullname','$email','$role','$type','$password')";


    if(mysqli_query($connect,$insert)){
      echo "Data inserted";
    } else {
      echo "Data not inserted" . mysqli_error($connect);
    }
}
 ?>  

Screenshot of output

1 个答案:

答案 0 :(得分:0)

基本上,您的代码是AngularJs,而不是Angular。

这是Angular 6中的类似代码

import { HttpClient } from '@angular/common/http';
export class UserComponent {
    constructor(private httpClient: HttpClient) { }

    insertData() {
        this.httpClient.post(
            "register_insert.php",
            {
                'email': this.email,
                'password': this.password,

            }
        ).subscribe((data) => {
            alert("inserted");
            this.email = null;
            this.password = null;
        });
    }
}